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 has been resolved from offline discussion and will continue with this approach in the short term until the long term approach to support such transformations in autorest itself is available.
public static CharFilter map(com.azure.search.documents.implementation.models.CharFilter obj) { if (obj instanceof PatternReplaceCharFilter) { return PatternReplaceCharFilterConverter.map((PatternReplaceCharFilter) obj); } if (obj instanceof MappingCharFilter) { return MappingCharFilterConverter.map((MappingCharFilter) obj); } throw LOGGER.logExceptionAsError(new RuntimeException(String.format(ABSTRACT_EXTERNAL_ERROR_MSG, obj.getClass().getSimpleName()))); }
if (obj instanceof PatternReplaceCharFilter) {
public static CharFilter map(com.azure.search.documents.implementation.models.CharFilter obj) { if (obj instanceof PatternReplaceCharFilter) { return PatternReplaceCharFilterConverter.map((PatternReplaceCharFilter) obj); } if (obj instanceof MappingCharFilter) { return MappingCharFilterConverter.map((MappingCharFilter) obj); } throw LOGGER.logExceptionAsError(new RuntimeException(String.format(ABSTRACT_EXTERNAL_ERROR_MSG, obj.getClass().getSimpleName()))); }
class converter. */
class converter. */
Is this something new we are introducing in this PR? Rather if `keyPhraseResultCollection` is empty return the same to client-side? What do other languages do here?
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } throw logger.logExceptionAsError( new TextAnalyticsException("None key Phrases extracted.", TextAnalyticsErrorCode.fromString("NoneKeyPhrasesExtracted").toString(), null)); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
new TextAnalyticsException("None key Phrases extracted.",
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link TextAnalyticsResultCollection} of * {@link ExtractKeyPhraseResult}. */ Mono<Response<TextAnalyticsResultCollection<ExtractKeyPhraseResult>>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link TextAnalyticsResultCollection} of {@link ExtractKeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link TextAnalyticsResultCollection} of * {@link ExtractKeyPhraseResult}. */ Mono<Response<TextAnalyticsResultCollection<ExtractKeyPhraseResult>>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link TextAnalyticsResultCollection} of {@link ExtractKeyPhraseResult}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link TextAnalyticsResultCollection} of * {@link ExtractKeyPhraseResult}. */ private Response<TextAnalyticsResultCollection<ExtractKeyPhraseResult>> toTextAnalyticsResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> new TextAnalyticsWarning(WarningCode.fromString(warning.getCode().toString()), warning.getMessage())) .collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new TextAnalyticsResultCollection<>(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link TextAnalyticsResultCollection} of {@link ExtractKeyPhraseResult} from a {@link SimpleResponse} * of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link TextAnalyticsResultCollection} of * {@link ExtractKeyPhraseResult}. */ private Mono<Response<TextAnalyticsResultCollection<ExtractKeyPhraseResult>>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toTextAnalyticsResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
Yes. I will update it to return empty.
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } throw logger.logExceptionAsError( new TextAnalyticsException("None key Phrases extracted.", TextAnalyticsErrorCode.fromString("NoneKeyPhrasesExtracted").toString(), null)); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
new TextAnalyticsException("None key Phrases extracted.",
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link TextAnalyticsResultCollection} of * {@link ExtractKeyPhraseResult}. */ Mono<Response<TextAnalyticsResultCollection<ExtractKeyPhraseResult>>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link TextAnalyticsResultCollection} of {@link ExtractKeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link TextAnalyticsResultCollection} of * {@link ExtractKeyPhraseResult}. */ Mono<Response<TextAnalyticsResultCollection<ExtractKeyPhraseResult>>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link TextAnalyticsResultCollection} of {@link ExtractKeyPhraseResult}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link TextAnalyticsResultCollection} of * {@link ExtractKeyPhraseResult}. */ private Response<TextAnalyticsResultCollection<ExtractKeyPhraseResult>> toTextAnalyticsResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> new TextAnalyticsWarning(WarningCode.fromString(warning.getCode().toString()), warning.getMessage())) .collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new TextAnalyticsResultCollection<>(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link TextAnalyticsResultCollection} of {@link ExtractKeyPhraseResult} from a {@link SimpleResponse} * of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link TextAnalyticsResultCollection} of * {@link ExtractKeyPhraseResult}. */ private Mono<Response<TextAnalyticsResultCollection<ExtractKeyPhraseResult>>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toTextAnalyticsResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
Is this required?
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return new KeyPhrasesCollection(null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return new KeyPhrasesCollection(null, null);
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
Can `keyPhraseResultCollection.getValue()` be null or empty?
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return new KeyPhrasesCollection(null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) {
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
Why do we have this in all the response mappers? Also, the comment is confusing. Either it gets executed or not. If it is expected to not be executed, then we should throw an exception when it does.
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } return detectLanguageResult.getPrimaryLanguage(); } return new DetectedLanguage(null, null, -1, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return new DetectedLanguage(null, null, -1, null);
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { DetectedLanguage detectedLanguage = null; for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } detectedLanguage = detectLanguageResult.getPrimaryLanguage(); } return detectedLanguage; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } return sentimentResult.getDocumentSentiment(); } return new DocumentSentiment(null, null, null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { DocumentSentiment documentSentiment = null; for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } documentSentiment = sentimentResult.getDocumentSentiment(); } return documentSentiment; }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
will remove it
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("184654c847d54432b8301a4b76f63045")) .endpoint("https: .buildClient(); List<TextDocumentInput> documents = Arrays.asList( new TextDocumentInput("A", "Satya Nadella is the CEO of Microsoft.").setLanguage("en"), new TextDocumentInput("B", "Elon Musk is the CEO of SpaceX and Tesla.").setLanguage("en") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true).setModelVersion("latest"); Response<RecognizeEntitiesResultCollection> entitiesBatchResultResponse = client.recognizeEntitiesBatchWithResponse(documents, requestOptions, Context.NONE); System.out.printf("Status code of request response: %d%n", entitiesBatchResultResponse.getStatusCode()); RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = entitiesBatchResultResponse.getValue(); System.out.printf("Results of Azure Text Analytics \"Entities Recognition\" Model, version: %s%n", recognizeEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); recognizeEntitiesResultCollection.forEach(entitiesResult -> { System.out.printf("%n%s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized entity: %s, entity category: %s, entity subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()) ); } }); }
.credential(new AzureKeyCredential("184654c847d54432b8301a4b76f63045"))
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<TextDocumentInput> documents = Arrays.asList( new TextDocumentInput("A", "Satya Nadella is the CEO of Microsoft.").setLanguage("en"), new TextDocumentInput("B", "Elon Musk is the CEO of SpaceX and Tesla.").setLanguage("en") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true).setModelVersion("latest"); Response<RecognizeEntitiesResultCollection> entitiesBatchResultResponse = client.recognizeEntitiesBatchWithResponse(documents, requestOptions, Context.NONE); System.out.printf("Status code of request response: %d%n", entitiesBatchResultResponse.getStatusCode()); RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = entitiesBatchResultResponse.getValue(); System.out.printf("Results of Azure Text Analytics \"Entities Recognition\" Model, version: %s%n", recognizeEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (RecognizeEntitiesResult entitiesResult : recognizeEntitiesResultCollection) { System.out.printf("%n%s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized entity: %s, entity category: %s, entity subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()) ); } } }
class RecognizeEntitiesBatchDocuments { /** * Main method to invoke this demo about how to recognize the entities of {@link TextDocumentInput} documents. * * @param args Unused arguments to the program. */ }
class RecognizeEntitiesBatchDocuments { /** * Main method to invoke this demo about how to recognize the entities of {@link TextDocumentInput} documents. * * @param args Unused arguments to the program. */ }
is the endpoint printed somewhere? do we need to rotate this key?
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("184654c847d54432b8301a4b76f63045")) .endpoint("https: .buildClient(); List<TextDocumentInput> documents = Arrays.asList( new TextDocumentInput("A", "Satya Nadella is the CEO of Microsoft.").setLanguage("en"), new TextDocumentInput("B", "Elon Musk is the CEO of SpaceX and Tesla.").setLanguage("en") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true).setModelVersion("latest"); Response<RecognizeEntitiesResultCollection> entitiesBatchResultResponse = client.recognizeEntitiesBatchWithResponse(documents, requestOptions, Context.NONE); System.out.printf("Status code of request response: %d%n", entitiesBatchResultResponse.getStatusCode()); RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = entitiesBatchResultResponse.getValue(); System.out.printf("Results of Azure Text Analytics \"Entities Recognition\" Model, version: %s%n", recognizeEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); recognizeEntitiesResultCollection.forEach(entitiesResult -> { System.out.printf("%n%s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized entity: %s, entity category: %s, entity subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()) ); } }); }
.credential(new AzureKeyCredential("184654c847d54432b8301a4b76f63045"))
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<TextDocumentInput> documents = Arrays.asList( new TextDocumentInput("A", "Satya Nadella is the CEO of Microsoft.").setLanguage("en"), new TextDocumentInput("B", "Elon Musk is the CEO of SpaceX and Tesla.").setLanguage("en") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true).setModelVersion("latest"); Response<RecognizeEntitiesResultCollection> entitiesBatchResultResponse = client.recognizeEntitiesBatchWithResponse(documents, requestOptions, Context.NONE); System.out.printf("Status code of request response: %d%n", entitiesBatchResultResponse.getStatusCode()); RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = entitiesBatchResultResponse.getValue(); System.out.printf("Results of Azure Text Analytics \"Entities Recognition\" Model, version: %s%n", recognizeEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (RecognizeEntitiesResult entitiesResult : recognizeEntitiesResultCollection) { System.out.printf("%n%s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized entity: %s, entity category: %s, entity subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()) ); } } }
class RecognizeEntitiesBatchDocuments { /** * Main method to invoke this demo about how to recognize the entities of {@link TextDocumentInput} documents. * * @param args Unused arguments to the program. */ }
class RecognizeEntitiesBatchDocuments { /** * Main method to invoke this demo about how to recognize the entities of {@link TextDocumentInput} documents. * * @param args Unused arguments to the program. */ }
you have to return or throw something. so i just return it. Is there a better way to refactor the code?
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return new KeyPhrasesCollection(null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return new KeyPhrasesCollection(null, null);
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
the valuable keyPhraseResultCollection, should change to response, so it will be response.getValue() As I know, response.getValue() should not be empty or null?
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return new KeyPhrasesCollection(null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) {
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
refactored the code. How is looks now?
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(keyPhraseResultCollection -> { for (ExtractKeyPhraseResult keyPhraseResult : keyPhraseResultCollection.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } return new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return new KeyPhrasesCollection(null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return new KeyPhrasesCollection(null, null);
Mono<KeyPhrasesCollection> extractKeyPhrasesSingleText(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document); textDocumentInput.setLanguage(language); return extractKeyPhrasesWithResponse(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { KeyPhrasesCollection keyPhrasesCollection = null; for (ExtractKeyPhraseResult keyPhraseResult : resultCollectionResponse.getValue()) { if (keyPhraseResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(keyPhraseResult.getError())); } keyPhrasesCollection = new KeyPhrasesCollection(keyPhraseResult.getKeyPhrases(), keyPhraseResult.getKeyPhrases().getWarnings()); } return keyPhrasesCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class ExtractKeyPhraseAsyncClient { private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract * keyphrase endpoint. * * @param service The proxy service used to perform REST calls. */ ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that returns a {@link KeyPhrasesCollection}. * * @param document A document. * @param language The language code. * * @return The {@link Mono} of {@link KeyPhrasesCollection} extracted key phrases strings. */ /** * Helper function for calling service with max overloaded parameters with {@link Response}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getExtractedKeyPhrasesResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper function for calling service with max overloaded parameters that returns a {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return getExtractedKeyPhrasesResponse(documents, options, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Helper method to convert the service response of {@link KeyPhraseResult} to {@link Response} * which contains {@link ExtractKeyPhrasesResultCollection}. * * @param response the {@link SimpleResponse} returned by the service. * * @return A {@link Response} which contains {@link ExtractKeyPhrasesResultCollection}. */ private Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final SimpleResponse<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { final String documentId = documentKeyPhrases.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, documentKeyPhrases.getStatistics() == null ? null : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, new KeyPhrasesCollection( new IterableStream<>(documentKeyPhrases.getKeyPhrases()), new IterableStream<>(documentKeyPhrases.getWarnings().stream().map(warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); }).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } final TextAnalyticsError error = toTextAnalyticsError(documentError.getError()); final String documentId = documentError.getId(); keyPhraseResultList.add(new ExtractKeyPhraseResult( documentId, null, error, null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } /** * Call the service with REST response, convert to a {@link Mono} of {@link Response} which contains * {@link ExtractKeyPhrasesResultCollection} from a {@link SimpleResponse} of {@link KeyPhraseResult}. * * @param documents A list of documents to extract key phrases for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A mono {@link Response} that contains {@link ExtractKeyPhrasesResultCollection}. */ private Mono<Response<ExtractKeyPhrasesResultCollection>> getExtractedKeyPhrasesResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.keyPhrasesWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of document - {}", documents.toString())) .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) .map(this::toExtractKeyPhrasesResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
Throw an exception will make java inconsistency with other languages.
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } return detectLanguageResult.getPrimaryLanguage(); } return new DetectedLanguage(null, null, -1, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return new DetectedLanguage(null, null, -1, null);
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { DetectedLanguage detectedLanguage = null; for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } detectedLanguage = detectLanguageResult.getPrimaryLanguage(); } return detectedLanguage; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } return sentimentResult.getDocumentSentiment(); } return new DocumentSentiment(null, null, null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { DocumentSentiment documentSentiment = null; for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } documentSentiment = sentimentResult.getDocumentSentiment(); } return documentSentiment; }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
could you expand on what the scenario is here? not sure why we need to create this fake object. How will the user consume/use this?
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } return detectLanguageResult.getPrimaryLanguage(); } return new DetectedLanguage(null, null, -1, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return new DetectedLanguage(null, null, -1, null);
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { DetectedLanguage detectedLanguage = null; for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } detectedLanguage = detectLanguageResult.getPrimaryLanguage(); } return detectedLanguage; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } return sentimentResult.getDocumentSentiment(); } return new DocumentSentiment(null, null, null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { DocumentSentiment documentSentiment = null; for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } documentSentiment = sentimentResult.getDocumentSentiment(); } return documentSentiment; }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
@maririos It is what we discussed afternoon. .NET return it as it is. The scenario is when user gives a single input document, internally, it called the batch API. And then we get the batch output result collection, which in here, `DetectLanguageResultCollection`, this class extends `IterableStream<DetectLanguageResult>`, So the `DetectLanguageResultCollection` should has only one `DetectLanguageResult`. but the fake object created here should not be executed, since `DetectLanguageResultCollection` should has only one.
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } return detectLanguageResult.getPrimaryLanguage(); } return new DetectedLanguage(null, null, -1, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return new DetectedLanguage(null, null, -1, null);
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { DetectedLanguage detectedLanguage = null; for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } detectedLanguage = detectLanguageResult.getPrimaryLanguage(); } return detectedLanguage; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } return sentimentResult.getDocumentSentiment(); } return new DocumentSentiment(null, null, null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { DocumentSentiment documentSentiment = null; for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } documentSentiment = sentimentResult.getDocumentSentiment(); } return documentSentiment; }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
@mssfang can be handled similarly https://github.com/Azure/azure-sdk-for-java/pull/11318/files#diff-8d0c97bfcab02df81ac3a72abd26a2a2R78-R89 Update the comment indicating that an empty result is returned when the service returns an empty collection.
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } return detectLanguageResult.getPrimaryLanguage(); } return new DetectedLanguage(null, null, -1, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
return new DetectedLanguage(null, null, -1, null);
public Mono<DetectedLanguage> detectLanguage(String document, String countryHint) { try { Objects.requireNonNull(document, "'document' cannot be null."); return detectLanguageBatch(Collections.singletonList(document), countryHint, null) .map(detectLanguageResultCollection -> { DetectedLanguage detectedLanguage = null; for (DetectLanguageResult detectLanguageResult : detectLanguageResultCollection) { if (detectLanguageResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(detectLanguageResult.getError())); } detectedLanguage = detectLanguageResult.getPrimaryLanguage(); } return detectedLanguage; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } return sentimentResult.getDocumentSentiment(); } return new DocumentSentiment(null, null, null, null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; static final String COGNITIVE_TRACING_NAMESPACE_VALUE = "Microsoft.CognitiveServices"; final DetectLanguageAsyncClient detectLanguageAsyncClient; final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; final RecognizeEntityAsyncClient recognizeEntityAsyncClient; final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@link TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each * service call goes through the {@link TextAnalyticsClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Text Analytics supported by this client library. * @param defaultCountryHint The default country hint. * @param defaultLanguage The default language. */ TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, String defaultCountryHint, String defaultLanguage) { this.service = service; this.serviceVersion = serviceVersion; this.defaultCountryHint = defaultCountryHint; this.defaultLanguage = defaultLanguage; this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** * Get default country hint code. * * @return the default country hint code */ public String getDefaultCountryHint() { return defaultCountryHint; } /** * Get default language when the builder is setup. * * @return the default language */ public String getDefaultLanguage() { return defaultLanguage; } /** * Returns the detected language and a confidence score between zero and one. Scores close to one indicate 100% * certainty that the identified language is true. * * This method will use the default country hint that sets up in * {@link TextAnalyticsClientBuilder * the country hint. * * <p><strong>Code sample</strong></p> * <p>Detects language in a document. Subscribes to the call asynchronously and prints out the detected language * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} containing the {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectedLanguage> detectLanguage(String document) { return detectLanguage(document, defaultCountryHint); } /** * Returns a {@link Response} contains the detected language and a confidence score between zero and one. Scores * close to one indicate 100% certainty that the identified language is true. * * <p><strong>Code sample</strong></p> * <p>Detects language with http response in a document with a provided country hint. Subscribes to the call * asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguage * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * * @return A {@link Mono} contains a {@link DetectedLanguage detected language} of the document. * * @throws NullPointerException if the document is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Returns the detected language for each of documents with the provided country hint and request option. * * <p><strong>Code sample</strong></p> * <p>Detects language in a list of documents with a provided country hint and request option for the batch. * Subscribes to the call asynchronously and prints out the detected language details when a response is received. * </p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of documents to detect languages for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not * specified. To remove this behavior you can reset this parameter by setting this value to empty string * {@code countryHint} = "" or "none". * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DetectLanguageResultCollection> detectLanguageBatch( Iterable<String> documents, String countryHint, TextAnalyticsRequestOptions options) { if (countryHint != null && countryHint.equalsIgnoreCase("none")) { countryHint = ""; } final String finalCountryHint = countryHint; try { return detectLanguageBatchWithResponse( mapByIndex(documents, (index, value) -> new DetectLanguageInput(index, value, finalCountryHint)), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the detected language for a batch of {@link DetectLanguageInput document} with provided request options. * * <p><strong>Code sample</strong></p> * <p>Detects language in a batch of {@link DetectLanguageInput document} with provided request options. Subscribes * to the call asynchronously and prints out the detected language details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.detectLanguageBatch * * @param documents The list of {@link DetectLanguageInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link DetectLanguageResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DetectLanguageResultCollection>> detectLanguageBatchWithResponse( Iterable<DetectLanguageInput> documents, TextAnalyticsRequestOptions options) { return detectLanguageAsyncClient.detectLanguageBatch(documents, options); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document. Subscribes to the call asynchronously and prints out the recognized entity * details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document The document to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document) { return recognizeEntities(document, defaultLanguage); } /** * Returns a list of general categorized entities in the provided document. * * For a list of supported entity types, check: <a href="https: * For a list of enabled languages, check: <a href="https: * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with provided language code. Subscribes to the call asynchronously and prints * out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeEntities * * @param document the text to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * * @return A {@link Mono} contains a {@link CategorizedEntityCollection recognized categorized entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CategorizedEntityCollection> recognizeEntities(String document, String language) { return recognizeEntityAsyncClient.recognizeEntities(document, language); } /** * Returns a list of general categorized entities for the provided list of documents with the provided language code * and request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a document with the provided language code. Subscribes to the call asynchronously and * prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of documents to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as * default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeEntitiesResultCollection> recognizeEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeEntitiesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of general categorized entities for the provided list of {@link TextDocumentInput document} with * provided request options. * * <p><strong>Code sample</strong></p> * <p>Recognize entities in a list of {@link TextDocumentInput document}. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeCategorizedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a {@link RecognizeEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeEntitiesResultCollection>> recognizeEntitiesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeEntityAsyncClient.recognizeEntitiesBatch(documents, options); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Recognize linked entities in a document. Subscribes to the call asynchronously and prints out the * entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document) { return recognizeLinkedEntities(document, defaultLanguage); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided document. See * <a href="https: * * <p>Recognize linked entities in a text with provided language code. Subscribes to the call asynchronously * and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntities * * @param document The document to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link LinkedEntityCollection recognized linked entities collection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LinkedEntityCollection> recognizeLinkedEntities(String document, String language) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntities(document, language); } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of documents with * provided language code and request options. * * See <a href="https: * * <p>Recognize linked entities in a list of documents with provided language code. Subscribes to the call * asynchronously and prints out the entity details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of documents to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RecognizeLinkedEntitiesResultCollection> recognizeLinkedEntitiesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return recognizeLinkedEntitiesBatchWithResponse(mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of * {@link TextDocumentInput document} with provided request options. * * See <a href="https: * * <p>Recognize linked entities in a list of {@link TextDocumentInput document} and provided request options to * show statistics. Subscribes to the call asynchronously and prints out the entity details when a response is * received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeLinkedEntitiesBatch * * @param documents A list of {@link TextDocumentInput documents} to recognize linked entities for. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} which contains a * {@link RecognizeLinkedEntitiesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RecognizeLinkedEntitiesResultCollection>> recognizeLinkedEntitiesBatchWithResponse(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesBatch(documents, options); } /** * Returns a list of strings denoting the key phrases in the document. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Extract key phrases in a document. Subscribes to the call asynchronously and prints out the * key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains a {@link KeyPhrasesCollection}. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document) { return extractKeyPhrases(document, defaultLanguage); } /** * Returns a list of strings denoting the key phrases in the document. * * See <a href="https: * * <p>Extract key phrases in a document with a provided language code. Subscribes to the call asynchronously and * prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrases * * @param document The document to be analyzed. For text length limits, maximum batch size, and supported text * encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains a {@link KeyPhrasesCollection} * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<KeyPhrasesCollection> extractKeyPhrases(String document, String language) { return extractKeyPhraseAsyncClient.extractKeyPhrasesSingleText(document, language); } /** * Returns a list of strings denoting the key phrases in the document with provided language code and request * options. * * See <a href="https: * * <p>Extract key phrases in a list of documents with a provided language and request options. Subscribes to the * call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExtractKeyPhrasesResultCollection> extractKeyPhrasesBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return extractKeyPhrasesBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a list of strings denoting the key phrases in the document with provided request options. * * See <a href="https: * * <p>Extract key phrases in a list of {@link TextDocumentInput document} with provided request options. * Subscribes to the call asynchronously and prints out the key phrases when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.extractKeyPhrasesBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link ExtractKeyPhrasesResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExtractKeyPhrasesResultCollection>> extractKeyPhrasesBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(documents, options); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * This method will use the default language that sets up in * {@link TextAnalyticsClientBuilder * the language. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document) { return analyzeSentiment(document, defaultLanguage); } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents. Subscribes to the call asynchronously and prints out the * sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment * * @param document The document to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for * English as default. * * @return A {@link Mono} contains the {@link DocumentSentiment analyzed document sentiment} of the document. * * @throws NullPointerException if {@code document} is {@code null}. * @throws TextAnalyticsException if the response returned with an {@link TextAnalyticsError error}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DocumentSentiment> analyzeSentiment(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return analyzeSentimentBatch(Collections.singletonList(document), language, null) .map(sentimentResultCollection -> { DocumentSentiment documentSentiment = null; for (AnalyzeSentimentResult sentimentResult : sentimentResultCollection) { if (sentimentResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(sentimentResult.getError())); } documentSentiment = sentimentResult.getDocumentSentiment(); } return documentSentiment; }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of documents with provided language code and request options. Subscribes to the * call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of documents to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param language The 2 letter ISO 639-1 representation of language for the document. If not set, uses "en" for * English as default. * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AnalyzeSentimentResultCollection> analyzeSentimentBatch( Iterable<String> documents, String language, TextAnalyticsRequestOptions options) { try { return analyzeSentimentBatchWithResponse( mapByIndex(documents, (index, value) -> { final TextDocumentInput textDocumentInput = new TextDocumentInput(index, value); textDocumentInput.setLanguage(language); return textDocumentInput; }), options).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns a sentiment prediction, as well as confidence scores for each sentiment label (Positive, Negative, and * Neutral) for the document and each sentence within it. * * <p>Analyze sentiment in a list of {@link TextDocumentInput document} with provided request options. Subscribes * to the call asynchronously and prints out the sentiment details when a response is received.</p> * * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentimentBatch * * @param documents A list of {@link TextDocumentInput documents} to be analyzed. * For text length limits, maximum batch size, and supported text encoding, see * <a href="https: * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents * and show statistics. * * @return A {@link Mono} contains a {@link Response} that contains a {@link AnalyzeSentimentResultCollection}. * * @throws NullPointerException if {@code documents} is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatchWithResponse( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { return analyzeSentimentAsyncClient.analyzeSentimentBatch(documents, options); } }
Is there a case where `authenticateWithConfidentialClientCache` would return `null`? If not I believe these could be merged into the `onErrorResume`.
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithConfidentialClientCache(request) .onErrorResume(t -> Mono.empty()) .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))); }
.switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request)));
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithConfidentialClientCache(request) .onErrorResume(t -> Mono.empty()) .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))); }
class ClientCertificateCredential implements TokenCredential { private final IdentityClient identityClient; /** * Creates a ClientSecretCredential with default identity client options. * @param tenantId the tenant ID of the application * @param clientId the client ID of the application * @param certificatePath the PEM file or PFX file containing the certificate * @param certificatePassword the password protecting the PFX file * @param identityClientOptions the options to configure the identity client */ ClientCertificateCredential(String tenantId, String clientId, String certificatePath, String certificatePassword, IdentityClientOptions identityClientOptions) { Objects.requireNonNull(certificatePath, "'certificatePath' cannot be null."); identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .certificatePath(certificatePath) .certificatePassword(certificatePassword) .identityClientOptions(identityClientOptions) .build(); } @Override }
class ClientCertificateCredential implements TokenCredential { private final IdentityClient identityClient; /** * Creates a ClientSecretCredential with default identity client options. * @param tenantId the tenant ID of the application * @param clientId the client ID of the application * @param certificatePath the PEM file or PFX file containing the certificate * @param certificatePassword the password protecting the PFX file * @param identityClientOptions the options to configure the identity client */ ClientCertificateCredential(String tenantId, String clientId, String certificatePath, String certificatePassword, IdentityClientOptions identityClientOptions) { Objects.requireNonNull(certificatePath, "'certificatePath' cannot be null."); identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .certificatePath(certificatePath) .certificatePassword(certificatePassword) .identityClientOptions(identityClientOptions) .build(); } @Override }
I don't know if we need the `Mono.defer` here, I believe `switchIfEmpty` only processes if the upstream returns empty otherwise it is never ran.
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithConfidentialClientCache(request) .onErrorResume(t -> Mono.empty()) .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))); }
.switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request)));
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithConfidentialClientCache(request) .onErrorResume(t -> Mono.empty()) .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))); }
class ClientCertificateCredential implements TokenCredential { private final IdentityClient identityClient; /** * Creates a ClientSecretCredential with default identity client options. * @param tenantId the tenant ID of the application * @param clientId the client ID of the application * @param certificatePath the PEM file or PFX file containing the certificate * @param certificatePassword the password protecting the PFX file * @param identityClientOptions the options to configure the identity client */ ClientCertificateCredential(String tenantId, String clientId, String certificatePath, String certificatePassword, IdentityClientOptions identityClientOptions) { Objects.requireNonNull(certificatePath, "'certificatePath' cannot be null."); identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .certificatePath(certificatePath) .certificatePassword(certificatePassword) .identityClientOptions(identityClientOptions) .build(); } @Override }
class ClientCertificateCredential implements TokenCredential { private final IdentityClient identityClient; /** * Creates a ClientSecretCredential with default identity client options. * @param tenantId the tenant ID of the application * @param clientId the client ID of the application * @param certificatePath the PEM file or PFX file containing the certificate * @param certificatePassword the password protecting the PFX file * @param identityClientOptions the options to configure the identity client */ ClientCertificateCredential(String tenantId, String clientId, String certificatePath, String certificatePassword, IdentityClientOptions identityClientOptions) { Objects.requireNonNull(certificatePath, "'certificatePath' cannot be null."); identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .certificatePath(certificatePath) .certificatePassword(certificatePassword) .identityClientOptions(identityClientOptions) .build(); } @Override }
Not needed, but given this has a lot of nesting and all other conditionals hit terminal states above could the `else` be removed for a regular code block?
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | IOException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } }
} else {
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Thoughts on merging all these to use their super class `GeneralSecurityException`.
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | IOException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } }
| NoSuchProviderException
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Would this be better off above attempting to retrieve the credential as this will fail without requiring IO or handling security? Basically, this is a lighter exception to have happen first.
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | IOException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } }
}
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Does `Mono.fromFuture` wrap the thrown exception into a `Mono.error` or will this need to be handled as a regular exception?
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options))); }
throw logger.logExceptionAsError(Exceptions.propagate(e));
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | IOException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
It could complete without calling `onNext()` so we cannot merge them.
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithConfidentialClientCache(request) .onErrorResume(t -> Mono.empty()) .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))); }
.switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request)));
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithConfidentialClientCache(request) .onErrorResume(t -> Mono.empty()) .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))); }
class ClientCertificateCredential implements TokenCredential { private final IdentityClient identityClient; /** * Creates a ClientSecretCredential with default identity client options. * @param tenantId the tenant ID of the application * @param clientId the client ID of the application * @param certificatePath the PEM file or PFX file containing the certificate * @param certificatePassword the password protecting the PFX file * @param identityClientOptions the options to configure the identity client */ ClientCertificateCredential(String tenantId, String clientId, String certificatePath, String certificatePassword, IdentityClientOptions identityClientOptions) { Objects.requireNonNull(certificatePath, "'certificatePath' cannot be null."); identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .certificatePath(certificatePath) .certificatePassword(certificatePassword) .identityClientOptions(identityClientOptions) .build(); } @Override }
class ClientCertificateCredential implements TokenCredential { private final IdentityClient identityClient; /** * Creates a ClientSecretCredential with default identity client options. * @param tenantId the tenant ID of the application * @param clientId the client ID of the application * @param certificatePath the PEM file or PFX file containing the certificate * @param certificatePassword the password protecting the PFX file * @param identityClientOptions the options to configure the identity client */ ClientCertificateCredential(String tenantId, String clientId, String certificatePath, String certificatePassword, IdentityClientOptions identityClientOptions) { Objects.requireNonNull(certificatePath, "'certificatePath' cannot be null."); identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .certificatePath(certificatePath) .certificatePassword(certificatePassword) .identityClientOptions(identityClientOptions) .build(); } @Override }
switchIfEmpty only processes the Mono if the upstream returns empty, but the method call `identityClient.authenticateWithConfidentialClient()` would be executed before the stream starts.
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithConfidentialClientCache(request) .onErrorResume(t -> Mono.empty()) .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))); }
.switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request)));
public Mono<AccessToken> getToken(TokenRequestContext request) { return identityClient.authenticateWithConfidentialClientCache(request) .onErrorResume(t -> Mono.empty()) .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request))); }
class ClientCertificateCredential implements TokenCredential { private final IdentityClient identityClient; /** * Creates a ClientSecretCredential with default identity client options. * @param tenantId the tenant ID of the application * @param clientId the client ID of the application * @param certificatePath the PEM file or PFX file containing the certificate * @param certificatePassword the password protecting the PFX file * @param identityClientOptions the options to configure the identity client */ ClientCertificateCredential(String tenantId, String clientId, String certificatePath, String certificatePassword, IdentityClientOptions identityClientOptions) { Objects.requireNonNull(certificatePath, "'certificatePath' cannot be null."); identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .certificatePath(certificatePath) .certificatePassword(certificatePassword) .identityClientOptions(identityClientOptions) .build(); } @Override }
class ClientCertificateCredential implements TokenCredential { private final IdentityClient identityClient; /** * Creates a ClientSecretCredential with default identity client options. * @param tenantId the tenant ID of the application * @param clientId the client ID of the application * @param certificatePath the PEM file or PFX file containing the certificate * @param certificatePassword the password protecting the PFX file * @param identityClientOptions the options to configure the identity client */ ClientCertificateCredential(String tenantId, String clientId, String certificatePath, String certificatePassword, IdentityClientOptions identityClientOptions) { Objects.requireNonNull(certificatePath, "'certificatePath' cannot be null."); identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .certificatePath(certificatePath) .certificatePassword(certificatePassword) .identityClientOptions(identityClientOptions) .build(); } @Override }
removed.
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | IOException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } }
} else {
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
works like a charm
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | IOException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } }
| NoSuchProviderException
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
I'm not sure how reactor handles it. Since it's not documented even if there's anything, I'm returning CompletableFuture.failedFuture() instead.
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options))); }
throw logger.logExceptionAsError(Exceptions.propagate(e));
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | IOException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Unfortunately the ConfidentialClientApplication.Builder requires the credential to be passed in the constructor of the builder, not as a builder setter. So the authority has to be set after the credential.
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | IOException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } }
}
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
the logic to build httpPipelineAdapter from line 177 - 193, can be extracted in a common helper method, and used in getPublicClient / getCofidentialClient methods.
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline);
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Why are we doing Exceptions.propagate and not directly converting to Runtime Exception ?
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); }
return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e)));
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Do we expect MSAL to return an expired token ?
public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); }
.filter(t -> !t.isExpired());
public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
That's not possible actually - the public client builder and the confidential client builder extends from a builder base that's not public. So from outside the MSAL library, the public client builder and confidential client builder are totally unrelated classes.
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline);
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
@alzimmermsft suggested this usage pattern to me.
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); }
return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e)));
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
No. But a non-expired IAuthenticationResult could be an expired AccessToken because of the offset. In my token refresh offset re-work, this line will be changed to `.filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(identityClientOptions.getTokenRefreshOffset())));` But for now this may look a little confusing.
public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); }
.filter(t -> !t.isExpired());
public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Actually I know a reason - if `e` is already a subclass of `RuntimeException`, wrapping it in another `RuntimeException` is bad. `Exceptions.propagate(e)` will check if `e` is a RuntimeException first and only wrap if not.
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); }
return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e)));
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Okay, But we already know, MalformedURLException is not a RuntimeException here. So, that check is redundant.
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); }
return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e)));
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
I am talking about this possible change/refactor which can be used in both getPublicClient and getConfidentialClient methods. `HttpPipelineAdapter httpPipelineAdapter = getHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } private HttpPipelineAdapter getHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { return new HttpPipelineAdapter(httpPipeline); } else { // If http client is set on the credential, then it should override the proxy options if any configured. HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { return new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() != null) { return null; } else { return new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } }`
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline);
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
I think we skip checkstyles on samples.
public static void main(String[] args) { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String modelId = "{model_Id}"; String formUrl = "{form_url}"; SyncPoller<OperationResult, List<RecognizedForm>> recognizeFormPoller = client.beginRecognizeCustomFormsFromUrl(formUrl, modelId, new RecognizeOptions() .setIncludeFieldElements(true)); List<RecognizedForm> recognizedForms = recognizeFormPoller.getFinalResult(); System.out.println("-------- RECOGNIZING FORM --------"); for (int i = 0; i < recognizedForms.size(); i++) { final RecognizedForm recognizedForm = recognizedForms.get(i); System.out.printf("Form %d has type: %s%n", i, recognizedForm.getFormType()); recognizedForm.getFields().forEach((fieldText, fieldValue) -> System.out.printf("Field %s has value %s " + "based on %s with a confidence score " + "of %.2f.%n", fieldText, fieldValue.getValue(), fieldValue.getValueData().getText(), fieldValue.getConfidence())); final List<FormPage> pages = recognizedForm.getPages(); for (int i1 = 0; i1 < pages.size(); i1++) { final FormPage formPage = pages.get(i1); System.out.printf("-------Recognizing Page %d 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().forEach(formContent -> { if (formContent instanceof FormWord) { FormWord formWordElement = (FormWord) (formContent); StringBuilder boundingBoxStr = new StringBuilder(); if (formWordElement.getBoundingBox() != null) { formWordElement.getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Word '%s' within bounding box %s with a confidence of %.2f.%n", formWordElement.getText(), boundingBoxStr, formWordElement.getConfidence()); } }); }); System.out.println(); } } } }
formWordElement.getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(),
public static void main(String[] args) { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String modelId = "{model_Id}"; String formUrl = "{form_url}"; SyncPoller<OperationResult, List<RecognizedForm>> recognizeFormPoller = client.beginRecognizeCustomFormsFromUrl(formUrl, modelId, new RecognizeOptions() .setIncludeFieldElements(true)); List<RecognizedForm> recognizedForms = recognizeFormPoller.getFinalResult(); for (int i = 0; i < recognizedForms.size(); i++) { final RecognizedForm recognizedForm = recognizedForms.get(i); System.out.printf("Form %d has type: %s%n", i, recognizedForm.getFormType()); recognizedForm.getFields().forEach((fieldText, fieldValue) -> System.out.printf("Field %s has value %s " + "based on %s with a confidence score " + "of %.2f.%n", fieldText, fieldValue.getValue(), fieldValue.getValueData().getText(), fieldValue.getConfidence())); final List<FormPage> pages = recognizedForm.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 FormWord) .map(formContent -> (FormWord) (formContent)) .forEach(formWordElement -> { StringBuilder boundingBoxStr = new StringBuilder(); if (formWordElement.getBoundingBox() != null) { formWordElement.getBoundingBox().getPoints() .forEach(point -> boundingBoxStr.append( String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Word '%s' within bounding box %s with a confidence of %.2f.%n", formWordElement.getText(), boundingBoxStr.toString(), formWordElement.getConfidence()); }); }); System.out.println(); } } } }
class GetBoundingBoxes { /** * Main method to invoke this demo. * * @param args Unused arguments to the program. */ }
class GetBoundingBoxes { /** * Main method to invoke this demo. * * @param args Unused arguments to the program. */ }
Refactored.
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline);
private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
That's correct. But at this point it's really a personal preference thing. I changed it to `new RuntimeException()` for the if check it saves. But one could argue in the future if more exceptions are thrown or this code path is refactored to merge with other paths that could throw RuntimeExceptions this could potentially be a point of failure. The point is, it's not critical.
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(result -> new MsalToken(result, options))); }
return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e)));
public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); applicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); applicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } }
Should this throw an exception if `httpClient` is null and proxy options are set?
private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } }
httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()));
private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
No - it's a valid scenario which is handled in line 177: https://github.com/Azure/azure-sdk-for-java/pull/11355/files/1c100d5ba097af9d5ba670b34d010f25d5606681#diff-56093106beda983b28894478869221c6R177. Basically, the only time we don't want to initialize the httpPipelineAdapter is when a proxy option is provided - in which case we pass the proxy option directly to MSAL for backward compatibility. New users should set the proxy options on the httpClient.
private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } }
httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()));
private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private ConfidentialClientApplication confidentialClientApplication; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private final String clientSecret; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String certificatePassword, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificatePassword = certificatePassword; this.options = options; } private ConfidentialClientApplication getConfidentialClientApplication() { if (confidentialClientApplication != null) { return confidentialClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(certificatePath)); credential = ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes)); } else { credential = ClientCredentialFactory.createFromCertificate( new FileInputStream(certificatePath), certificatePassword); } } catch (IOException | GeneralSecurityException e) { throw logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else { throw logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path")); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { applicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getConfidentialClientPersistenceSettings())); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } this.confidentialClientApplication = applicationBuilder.build(); return this.confidentialClientApplication; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPublicClientPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return Mono.fromFuture(() -> getConfidentialClientApplication().acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(ar -> new MsalToken(ar, options)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(result -> new MsalToken(result, options))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } }
why is this final and the rest are not
public static void main(final String[] args) { FormTrainingClient client = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String targetResourceId = "target-resource-Id"; String targetResourceRegion = "target-resource-region"; final String copyModelId = "copy-model-Id"; final CopyAuthorization modelCopyAuthorization = client.getCopyAuthorization(targetResourceId, targetResourceRegion); SyncPoller<OperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(copyModelId, modelCopyAuthorization); CustomFormModelInfo modelCopy = copyPoller.getFinalResult(); System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " last updated on: %s.%n", modelCopy.getModelId(), modelCopy.getStatus(), modelCopy.getCreatedOn(), modelCopy.getLastUpdatedOn()); }
final String copyModelId = "copy-model-Id";
public static void main(final String[] args) { FormTrainingClient sourceClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); FormTrainingClient targetClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String targetResourceId = "target-resource-Id"; String targetResourceRegion = "target-resource-region"; CopyAuthorization modelCopyAuthorization = targetClient.getCopyAuthorization(targetResourceId, targetResourceRegion); String copyModelId = "copy-model-Id"; SyncPoller<OperationResult, CustomFormModelInfo> copyPoller = sourceClient.beginCopyModel(copyModelId, modelCopyAuthorization); copyPoller.waitForCompletion(); CustomFormModel copiedModel = targetClient.getCustomModel(modelCopyAuthorization.getModelId()); System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " transfer completed on: %s.%n", copiedModel.getModelId(), copiedModel.getModelStatus(), copiedModel.getRequestedOn(), copiedModel.getCompletedOn()); }
class CopyModel { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
class CopyModel { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
Why are these final, but the above variables in the code snippet not
public void getCopyAuthorization() { final String resourceId = "target-resource-Id"; final String resourceRegion = "target-resource-region"; formTrainingAsyncClient.getCopyAuthorization(resourceId, resourceRegion) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, " + "target resource Id; %s, target resource region: %s%n", copyAuthorization.getModelId(), copyAuthorization.getAccessToken(), copyAuthorization.getExpirationDateTimeTicks(), copyAuthorization.getResourceId(), copyAuthorization.getResourceRegion() )); }
final String resourceId = "target-resource-Id";
public void getCopyAuthorization() { String resourceId = "target-resource-Id"; String resourceRegion = "target-resource-region"; formTrainingAsyncClient.getCopyAuthorization(resourceId, resourceRegion) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, " + "target resource Id; %s, target resource region: %s%n", copyAuthorization.getModelId(), copyAuthorization.getAccessToken(), copyAuthorization.getExpiresOn(), copyAuthorization.getResourceId(), copyAuthorization.getResourceRegion() )); }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormTrainingClientBuilder().buildAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormTrainingClientBuilder().buildAsyncClient(); } /** * Code snippet for creating a {@link FormTrainingAsyncClient} with pipeline */ public void createFormTrainingAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormTrainingAsyncClient formTrainingAsyncClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; formTrainingAsyncClient.beginTraining(trainingFilesUrl, useTrainingLabels).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient * with options */ public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix("Invoice"); formTrainingAsyncClient.beginTraining(trainingFilesUrl, true, trainModelOptions, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginCopy() { String resourceId = "target-resource-Id"; String resourceRegion = "target-resource-region"; String copyModelId = "copy-model-Id"; formTrainingAsyncClient.getCopyAuthorization(resourceId, resourceRegion) .subscribe(copyAuthorization -> formTrainingAsyncClient.beginCopyModel(copyModelId, copyAuthorization) .subscribe(copyPoller -> copyPoller.getFinalResult().subscribe(customFormModelInfo -> { System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " last updated on: %s.%n", customFormModelInfo.getModelId(), customFormModelInfo.getStatus(), customFormModelInfo.getCreatedOn(), customFormModelInfo.getLastUpdatedOn()); }))); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginCopyOverload() { String resourceId = "target-resource-Id"; String resourceRegion = "target-resource-region"; String copyModelId = "copy-model-Id"; formTrainingAsyncClient.getCopyAuthorization(resourceId, resourceRegion) .subscribe(copyAuthorization -> formTrainingAsyncClient.beginCopyModel(copyModelId, copyAuthorization, Duration.ofSeconds(5)).subscribe(copyPoller -> copyPoller.getFinalResult().subscribe(customFormModelInfo -> { System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " last updated on: %s.%n", customFormModelInfo.getModelId(), customFormModelInfo.getStatus(), customFormModelInfo.getCreatedOn(), customFormModelInfo.getLastUpdatedOn()); }))); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCopyAuthorizationWithResponse() { final String resourceId = "target-resource-Id"; final String resourceRegion = "target-resource-region"; formTrainingAsyncClient.getCopyAuthorizationWithResponse(resourceId, resourceRegion) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization response status: %s, for model id: %s, access token: %s, " + "expiration time: %s, target resource Id; %s, target resource region: %s%n", copyAuthorization.getStatusCode(), copyAuthorization.getValue().getModelId(), copyAuthorization.getValue().getAccessToken(), copyAuthorization.getValue().getExpirationDateTimeTicks(), copyAuthorization.getValue().getResourceId(), copyAuthorization.getValue().getResourceRegion() )); } }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormTrainingClientBuilder().buildAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormTrainingClientBuilder().buildAsyncClient(); } /** * Code snippet for creating a {@link FormTrainingAsyncClient} with pipeline */ public void createFormTrainingAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormTrainingAsyncClient formTrainingAsyncClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; formTrainingAsyncClient.beginTraining(trainingFilesUrl, useTrainingLabels).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubmodels().forEach(customFormSubmodel -> customFormSubmodel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient * with options */ public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainingFileFilter trainingFileFilter = new TrainingFileFilter().setIncludeSubFolders(false).setPrefix("Invoice"); formTrainingAsyncClient.beginTraining(trainingFilesUrl, true, trainingFileFilter, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubmodels().forEach(customFormSubmodel -> customFormSubmodel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubmodels().forEach(customFormSubmodel -> customFormSubmodel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubmodels().forEach(customFormSubmodel -> customFormSubmodel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void listCustomModels() { formTrainingAsyncClient.listCustomModels().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getRequestedOn(), customModel.getCompletedOn())); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginCopy() { String resourceId = "target-resource-Id"; String resourceRegion = "target-resource-region"; String copyModelId = "copy-model-Id"; formTrainingAsyncClient.getCopyAuthorization(resourceId, resourceRegion) .subscribe(copyAuthorization -> formTrainingAsyncClient.beginCopyModel(copyModelId, copyAuthorization) .subscribe(copyPoller -> copyPoller.getFinalResult().subscribe(customFormModelInfo -> { System.out.printf("Copied model has model Id: %s, model status: %s, was requested on: %s," + " transfer completed on: %s.%n", customFormModelInfo.getModelId(), customFormModelInfo.getStatus(), customFormModelInfo.getRequestedOn(), customFormModelInfo.getCompletedOn()); }))); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginCopyOverload() { String resourceId = "target-resource-Id"; String resourceRegion = "target-resource-region"; String copyModelId = "copy-model-Id"; formTrainingAsyncClient.getCopyAuthorization(resourceId, resourceRegion) .subscribe(copyAuthorization -> formTrainingAsyncClient.beginCopyModel(copyModelId, copyAuthorization, Duration.ofSeconds(5)).subscribe(copyPoller -> copyPoller.getFinalResult().subscribe(customFormModelInfo -> { System.out.printf("Copied model has model Id: %s, model status: %s, was requested on: %s," + "transfer completed on: %s.%n", customFormModelInfo.getModelId(), customFormModelInfo.getStatus(), customFormModelInfo.getRequestedOn(), customFormModelInfo.getCompletedOn()); }))); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCopyAuthorizationWithResponse() { String resourceId = "target-resource-Id"; String resourceRegion = "target-resource-region"; formTrainingAsyncClient.getCopyAuthorizationWithResponse(resourceId, resourceRegion) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization response status: %s, for model id: %s, access token: %s, " + "expiration time: %s, target resource Id; %s, target resource region: %s%n", copyAuthorization.getStatusCode(), copyAuthorization.getValue().getModelId(), copyAuthorization.getValue().getAccessToken(), copyAuthorization.getValue().getExpiresOn(), copyAuthorization.getValue().getResourceId(), copyAuthorization.getValue().getResourceRegion() )); } }
I will update this to not be final, it doesn't add a lot and will avoid too much of code in the user-samples.
public static void main(final String[] args) { FormTrainingClient client = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String targetResourceId = "target-resource-Id"; String targetResourceRegion = "target-resource-region"; final String copyModelId = "copy-model-Id"; final CopyAuthorization modelCopyAuthorization = client.getCopyAuthorization(targetResourceId, targetResourceRegion); SyncPoller<OperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(copyModelId, modelCopyAuthorization); CustomFormModelInfo modelCopy = copyPoller.getFinalResult(); System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " last updated on: %s.%n", modelCopy.getModelId(), modelCopy.getStatus(), modelCopy.getCreatedOn(), modelCopy.getLastUpdatedOn()); }
final String copyModelId = "copy-model-Id";
public static void main(final String[] args) { FormTrainingClient sourceClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); FormTrainingClient targetClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String targetResourceId = "target-resource-Id"; String targetResourceRegion = "target-resource-region"; CopyAuthorization modelCopyAuthorization = targetClient.getCopyAuthorization(targetResourceId, targetResourceRegion); String copyModelId = "copy-model-Id"; SyncPoller<OperationResult, CustomFormModelInfo> copyPoller = sourceClient.beginCopyModel(copyModelId, modelCopyAuthorization); copyPoller.waitForCompletion(); CustomFormModel copiedModel = targetClient.getCustomModel(modelCopyAuthorization.getModelId()); System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " transfer completed on: %s.%n", copiedModel.getModelId(), copiedModel.getModelStatus(), copiedModel.getRequestedOn(), copiedModel.getCompletedOn()); }
class CopyModel { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
class CopyModel { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
it will be good to clarify that this is the client that contains the model we want to copy
public static void main(final String[] args) { FormTrainingClient client = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String targetResourceId = "target-resource-Id"; String targetResourceRegion = "target-resource-region"; final String copyModelId = "copy-model-Id"; final CopyAuthorization modelCopyAuthorization = client.getCopyAuthorization(targetResourceId, targetResourceRegion); SyncPoller<OperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(copyModelId, modelCopyAuthorization); CustomFormModelInfo modelCopy = copyPoller.getFinalResult(); System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " last updated on: %s.%n", modelCopy.getModelId(), modelCopy.getStatus(), modelCopy.getCreatedOn(), modelCopy.getLastUpdatedOn()); }
public static void main(final String[] args) { FormTrainingClient sourceClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); FormTrainingClient targetClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String targetResourceId = "target-resource-Id"; String targetResourceRegion = "target-resource-region"; CopyAuthorization modelCopyAuthorization = targetClient.getCopyAuthorization(targetResourceId, targetResourceRegion); String copyModelId = "copy-model-Id"; SyncPoller<OperationResult, CustomFormModelInfo> copyPoller = sourceClient.beginCopyModel(copyModelId, modelCopyAuthorization); copyPoller.waitForCompletion(); CustomFormModel copiedModel = targetClient.getCustomModel(modelCopyAuthorization.getModelId()); System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " transfer completed on: %s.%n", copiedModel.getModelId(), copiedModel.getModelStatus(), copiedModel.getRequestedOn(), copiedModel.getCompletedOn()); }
class CopyModel { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
class CopyModel { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
good to add a comment saying this is the id of the model we want to copy
public static void main(final String[] args) { FormTrainingClient client = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String targetResourceId = "target-resource-Id"; String targetResourceRegion = "target-resource-region"; final String copyModelId = "copy-model-Id"; final CopyAuthorization modelCopyAuthorization = client.getCopyAuthorization(targetResourceId, targetResourceRegion); SyncPoller<OperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(copyModelId, modelCopyAuthorization); CustomFormModelInfo modelCopy = copyPoller.getFinalResult(); System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " last updated on: %s.%n", modelCopy.getModelId(), modelCopy.getStatus(), modelCopy.getCreatedOn(), modelCopy.getLastUpdatedOn()); }
final String copyModelId = "copy-model-Id";
public static void main(final String[] args) { FormTrainingClient sourceClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); FormTrainingClient targetClient = new FormTrainingClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); String targetResourceId = "target-resource-Id"; String targetResourceRegion = "target-resource-region"; CopyAuthorization modelCopyAuthorization = targetClient.getCopyAuthorization(targetResourceId, targetResourceRegion); String copyModelId = "copy-model-Id"; SyncPoller<OperationResult, CustomFormModelInfo> copyPoller = sourceClient.beginCopyModel(copyModelId, modelCopyAuthorization); copyPoller.waitForCompletion(); CustomFormModel copiedModel = targetClient.getCustomModel(modelCopyAuthorization.getModelId()); System.out.printf("Copied model has model Id: %s, model status: %s, was created on: %s," + " transfer completed on: %s.%n", copiedModel.getModelId(), copiedModel.getModelStatus(), copiedModel.getRequestedOn(), copiedModel.getCompletedOn()); }
class CopyModel { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
class CopyModel { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
This shouldn't work. modelId's should be different
void beginCopy(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); final CustomFormModel actualModel = syncPoller.getFinalResult(); beginCopyRunner((resourceId, resourceRegion) -> { final Mono<CopyAuthorization> target = client.getCopyAuthorization(resourceId, resourceRegion); final PollerFlux<OperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(actualModel.getModelId(), target.block()); final CustomFormModelInfo copyModel = copyPoller.getSyncPoller().getFinalResult(); assertEquals(actualModel.getModelId(), copyModel.getModelId()); assertNotNull(actualModel.getCreatedOn()); assertNotNull(actualModel.getLastUpdatedOn()); assertEquals(CustomFormModelStatus.fromString("succeeded"), copyModel.getStatus()); }); }); }
assertEquals(actualModel.getModelId(), copyModel.getModelId());
void beginCopy(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
class FormTrainingAsyncClientTest extends FormTrainingClientTestBase { static final String EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION = "Status code 400, \"{\"error\":{\"code\":\"1002\",\"message\":\"Copy request is invalid. Field 'TargetResourceRegion' must be a valid Azure region name.\"}}\""; private FormTrainingAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); AzureKeyCredential credential = (getTestMode() == TestMode.PLAYBACK) ? new AzureKeyCredential(INVALID_KEY) : new AzureKeyCredential(getApiKey()); builder.credential(credential); return builder.buildAsyncClient(); } /** * Verifies that an exception is thrown for null model Id parameter. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getCustomModel(null)).verifyError(); } /** * Verifies that an exception is thrown for invalid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); getCustomModelInvalidModelIdRunner(invalidModelId -> StepVerifier.create(client.getCustomModel(invalidModelId)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)).verify()); } /** * Verifies custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModelWithResponse(trainedModel.getModelId())).assertNext(customFormModelResponse -> { assertEquals(customFormModelResponse.getStatusCode(), HttpResponseStatus.OK.code()); validateCustomModelData(syncPoller.getFinalResult(), false); }); }); } /** * Verifies unlabeled custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedUnlabeledModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModel(trainedUnlabeledModel.getModelId())) .assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(), false)); }); } /** * Verifies labeled custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedLabeledModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModel(trainedLabeledModel.getModelId())) .assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(), true)); }); } /** * Verifies account properties returned for a subscription account. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void validGetAccountProperties(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getAccountProperties()) .assertNext(accountProperties -> validateAccountProperties(getExpectedAccountProperties(), accountProperties)) .verifyComplete(); } /** * Verifies account properties returned with an Http Response for a subscription account. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void validGetAccountPropertiesWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getAccountProperties()) .assertNext(accountProperties -> validateAccountProperties(getExpectedAccountProperties(), accountProperties)) .verifyComplete(); } /** * Verifies that an exception is thrown for invalid status model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void deleteModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.deleteModel(INVALID_MODEL_ID)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)) .verify(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(storageSASUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId())) .assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code())) .verifyComplete(); StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId())) .verifyErrorSatisfies(throwable -> throwable.getMessage().contains(HttpResponseStatus.NOT_FOUND.toString())); }); } /** * Test for listing all models information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getModelInfos(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getModelInfos()) .thenConsumeWhile(customFormModelInfo -> customFormModelInfo.getModelId() != null && customFormModelInfo.getCreatedOn() != null && customFormModelInfo.getLastUpdatedOn() != null && customFormModelInfo.getStatus() != null) .verifyComplete(); } /** * Verifies that an exception is thrown for null source url input. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingNullInput(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); NullPointerException thrown = assertThrows( NullPointerException.class, () -> client.beginTraining(null, false).getSyncPoller().getFinalResult()); assertTrue(thrown.getMessage().equals(NULL_SOURCE_URL_ERROR)); } /** * Verifies the result of the training operation for a valid labeled model Id and training set Url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingLabeledResult(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(storageSASUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); validateCustomModelData(syncPoller.getFinalResult(), true); }); } /** * Verifies the result of the training operation for a valid unlabeled model Id and training set Url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingUnlabeledResult(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((storageSASUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(storageSASUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); validateCustomModelData(syncPoller.getFinalResult(), false); }); } /** * Verifies the result of the copy operation for valid parameters. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils /** * Verifies the Invalid region ErrorResponseException is thrown for invalid region input to copy operation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils void beginCopyInvalidRegion(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); final CustomFormModel actualModel = syncPoller.getFinalResult(); beginCopyInvalidRegionRunner((resourceId, resourceRegion) -> { final Mono<CopyAuthorization> target = client.getCopyAuthorization(resourceId, resourceRegion); final PollerFlux<OperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(actualModel.getModelId(), target.block()); Exception thrown = assertThrows(ErrorResponseException.class, () -> copyPoller.getSyncPoller().getFinalResult()); assertEquals(EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION, thrown.getMessage()); }); }); } /** * Verifies the result of the copy authorization for valid parameters. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils void copyAuthorization(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginCopyRunner((resourceId, resourceRegion) -> StepVerifier.create(client.getCopyAuthorization(resourceId, resourceRegion)) .assertNext(copyAuthorization -> validateCopyAuthorizationResult(resourceId, resourceRegion, copyAuthorization)) .verifyComplete() ); } }
class FormTrainingAsyncClientTest extends FormTrainingClientTestBase { static final String EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION = "Status code 400, \"{\"error\":{\"code\":\"1002\",\"message\":\"Copy request is invalid. Field 'TargetResourceRegion' must be a valid Azure region name.\"}}\""; private FormTrainingAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); AzureKeyCredential credential = (getTestMode() == TestMode.PLAYBACK) ? new AzureKeyCredential(INVALID_KEY) : new AzureKeyCredential(getApiKey()); builder.credential(credential); return builder.buildAsyncClient(); } /** * Verifies that an exception is thrown for null model Id parameter. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getCustomModel(null)).verifyError(); } /** * Verifies that an exception is thrown for invalid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); getCustomModelInvalidModelIdRunner(invalidModelId -> StepVerifier.create(client.getCustomModel(invalidModelId)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)).verify()); } /** * Verifies custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModelWithResponse(trainedModel.getModelId())).assertNext(customFormModelResponse -> { assertEquals(customFormModelResponse.getStatusCode(), HttpResponseStatus.OK.code()); validateCustomModelData(syncPoller.getFinalResult(), false); }); }); } /** * Verifies unlabeled custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedUnlabeledModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModel(trainedUnlabeledModel.getModelId())) .assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(), false)); }); } /** * Verifies labeled custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedLabeledModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModel(trainedLabeledModel.getModelId())) .assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(), true)); }); } /** * Verifies account properties returned for a subscription account. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void validGetAccountProperties(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getAccountProperties()) .assertNext(accountProperties -> validateAccountProperties(getExpectedAccountProperties(), accountProperties)) .verifyComplete(); } /** * Verifies account properties returned with an Http Response for a subscription account. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void validGetAccountPropertiesWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getAccountProperties()) .assertNext(accountProperties -> validateAccountProperties(getExpectedAccountProperties(), accountProperties)) .verifyComplete(); } /** * Verifies that an exception is thrown for invalid status model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void deleteModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.deleteModel(INVALID_MODEL_ID)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)) .verify(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId())) .assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code())) .verifyComplete(); StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId())) .verifyErrorSatisfies(throwable -> assertTrue(throwable.getMessage().contains("404"))); }); } /** * Test for listing all models information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void listCustomModels(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.listCustomModels()) .thenConsumeWhile(customFormModelInfo -> customFormModelInfo.getModelId() != null && customFormModelInfo.getRequestedOn() != null && customFormModelInfo.getCompletedOn() != null && customFormModelInfo.getStatus() != null) .verifyComplete(); } /** * Verifies that an exception is thrown for null source url input. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingNullInput(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); NullPointerException thrown = assertThrows( NullPointerException.class, () -> client.beginTraining(null, false).getSyncPoller().getFinalResult()); assertTrue(thrown.getMessage().equals(NULL_SOURCE_URL_ERROR)); } /** * Verifies the result of the training operation for a valid labeled model Id and training set Url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingLabeledResult(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); validateCustomModelData(syncPoller.getFinalResult(), true); }); } /** * Verifies the result of the training operation for a valid unlabeled model Id and training set Url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingUnlabeledResult(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); validateCustomModelData(syncPoller.getFinalResult(), false); }); } /** * Verifies the result of the copy operation for valid parameters. */ }
when this is enabled, this shouldn't work either
void beginCopy(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); final CustomFormModel actualModel = syncPoller.getFinalResult(); beginCopyRunner((resourceId, resourceRegion) -> { final Mono<CopyAuthorization> target = client.getCopyAuthorization(resourceId, resourceRegion); final PollerFlux<OperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(actualModel.getModelId(), target.block()); final CustomFormModelInfo copyModel = copyPoller.getSyncPoller().getFinalResult(); assertEquals(actualModel.getModelId(), copyModel.getModelId()); assertNotNull(actualModel.getCreatedOn()); assertNotNull(actualModel.getLastUpdatedOn()); assertEquals(CustomFormModelStatus.fromString("succeeded"), copyModel.getStatus()); }); }); }
void beginCopy(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
class FormTrainingAsyncClientTest extends FormTrainingClientTestBase { static final String EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION = "Status code 400, \"{\"error\":{\"code\":\"1002\",\"message\":\"Copy request is invalid. Field 'TargetResourceRegion' must be a valid Azure region name.\"}}\""; private FormTrainingAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); AzureKeyCredential credential = (getTestMode() == TestMode.PLAYBACK) ? new AzureKeyCredential(INVALID_KEY) : new AzureKeyCredential(getApiKey()); builder.credential(credential); return builder.buildAsyncClient(); } /** * Verifies that an exception is thrown for null model Id parameter. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getCustomModel(null)).verifyError(); } /** * Verifies that an exception is thrown for invalid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); getCustomModelInvalidModelIdRunner(invalidModelId -> StepVerifier.create(client.getCustomModel(invalidModelId)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)).verify()); } /** * Verifies custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModelWithResponse(trainedModel.getModelId())).assertNext(customFormModelResponse -> { assertEquals(customFormModelResponse.getStatusCode(), HttpResponseStatus.OK.code()); validateCustomModelData(syncPoller.getFinalResult(), false); }); }); } /** * Verifies unlabeled custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedUnlabeledModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModel(trainedUnlabeledModel.getModelId())) .assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(), false)); }); } /** * Verifies labeled custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedLabeledModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModel(trainedLabeledModel.getModelId())) .assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(), true)); }); } /** * Verifies account properties returned for a subscription account. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void validGetAccountProperties(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getAccountProperties()) .assertNext(accountProperties -> validateAccountProperties(getExpectedAccountProperties(), accountProperties)) .verifyComplete(); } /** * Verifies account properties returned with an Http Response for a subscription account. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void validGetAccountPropertiesWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getAccountProperties()) .assertNext(accountProperties -> validateAccountProperties(getExpectedAccountProperties(), accountProperties)) .verifyComplete(); } /** * Verifies that an exception is thrown for invalid status model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void deleteModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.deleteModel(INVALID_MODEL_ID)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)) .verify(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(storageSASUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId())) .assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code())) .verifyComplete(); StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId())) .verifyErrorSatisfies(throwable -> throwable.getMessage().contains(HttpResponseStatus.NOT_FOUND.toString())); }); } /** * Test for listing all models information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getModelInfos(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getModelInfos()) .thenConsumeWhile(customFormModelInfo -> customFormModelInfo.getModelId() != null && customFormModelInfo.getCreatedOn() != null && customFormModelInfo.getLastUpdatedOn() != null && customFormModelInfo.getStatus() != null) .verifyComplete(); } /** * Verifies that an exception is thrown for null source url input. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingNullInput(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); NullPointerException thrown = assertThrows( NullPointerException.class, () -> client.beginTraining(null, false).getSyncPoller().getFinalResult()); assertTrue(thrown.getMessage().equals(NULL_SOURCE_URL_ERROR)); } /** * Verifies the result of the training operation for a valid labeled model Id and training set Url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingLabeledResult(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(storageSASUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); validateCustomModelData(syncPoller.getFinalResult(), true); }); } /** * Verifies the result of the training operation for a valid unlabeled model Id and training set Url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingUnlabeledResult(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((storageSASUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(storageSASUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); validateCustomModelData(syncPoller.getFinalResult(), false); }); } /** * Verifies the result of the copy operation for valid parameters. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils /** * Verifies the Invalid region ErrorResponseException is thrown for invalid region input to copy operation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils void beginCopyInvalidRegion(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); final CustomFormModel actualModel = syncPoller.getFinalResult(); beginCopyInvalidRegionRunner((resourceId, resourceRegion) -> { final Mono<CopyAuthorization> target = client.getCopyAuthorization(resourceId, resourceRegion); final PollerFlux<OperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(actualModel.getModelId(), target.block()); Exception thrown = assertThrows(ErrorResponseException.class, () -> copyPoller.getSyncPoller().getFinalResult()); assertEquals(EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION, thrown.getMessage()); }); }); } /** * Verifies the result of the copy authorization for valid parameters. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils void copyAuthorization(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginCopyRunner((resourceId, resourceRegion) -> StepVerifier.create(client.getCopyAuthorization(resourceId, resourceRegion)) .assertNext(copyAuthorization -> validateCopyAuthorizationResult(resourceId, resourceRegion, copyAuthorization)) .verifyComplete() ); } }
class FormTrainingAsyncClientTest extends FormTrainingClientTestBase { static final String EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION = "Status code 400, \"{\"error\":{\"code\":\"1002\",\"message\":\"Copy request is invalid. Field 'TargetResourceRegion' must be a valid Azure region name.\"}}\""; private FormTrainingAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); AzureKeyCredential credential = (getTestMode() == TestMode.PLAYBACK) ? new AzureKeyCredential(INVALID_KEY) : new AzureKeyCredential(getApiKey()); builder.credential(credential); return builder.buildAsyncClient(); } /** * Verifies that an exception is thrown for null model Id parameter. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getCustomModel(null)).verifyError(); } /** * Verifies that an exception is thrown for invalid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); getCustomModelInvalidModelIdRunner(invalidModelId -> StepVerifier.create(client.getCustomModel(invalidModelId)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)).verify()); } /** * Verifies custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModelWithResponse(trainedModel.getModelId())).assertNext(customFormModelResponse -> { assertEquals(customFormModelResponse.getStatusCode(), HttpResponseStatus.OK.code()); validateCustomModelData(syncPoller.getFinalResult(), false); }); }); } /** * Verifies unlabeled custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedUnlabeledModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModel(trainedUnlabeledModel.getModelId())) .assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(), false)); }); } /** * Verifies labeled custom model info returned with response for a valid model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void getCustomModelLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel trainedLabeledModel = syncPoller.getFinalResult(); StepVerifier.create(client.getCustomModel(trainedLabeledModel.getModelId())) .assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(), true)); }); } /** * Verifies account properties returned for a subscription account. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void validGetAccountProperties(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getAccountProperties()) .assertNext(accountProperties -> validateAccountProperties(getExpectedAccountProperties(), accountProperties)) .verifyComplete(); } /** * Verifies account properties returned with an Http Response for a subscription account. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void validGetAccountPropertiesWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getAccountProperties()) .assertNext(accountProperties -> validateAccountProperties(getExpectedAccountProperties(), accountProperties)) .verifyComplete(); } /** * Verifies that an exception is thrown for invalid status model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void deleteModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.deleteModel(INVALID_MODEL_ID)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)) .verify(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId())) .assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code())) .verifyComplete(); StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId())) .verifyErrorSatisfies(throwable -> assertTrue(throwable.getMessage().contains("404"))); }); } /** * Test for listing all models information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void listCustomModels(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.listCustomModels()) .thenConsumeWhile(customFormModelInfo -> customFormModelInfo.getModelId() != null && customFormModelInfo.getRequestedOn() != null && customFormModelInfo.getCompletedOn() != null && customFormModelInfo.getStatus() != null) .verifyComplete(); } /** * Verifies that an exception is thrown for null source url input. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingNullInput(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); NullPointerException thrown = assertThrows( NullPointerException.class, () -> client.beginTraining(null, false).getSyncPoller().getFinalResult()); assertTrue(thrown.getMessage().equals(NULL_SOURCE_URL_ERROR)); } /** * Verifies the result of the training operation for a valid labeled model Id and training set Url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingLabeledResult(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); validateCustomModelData(syncPoller.getFinalResult(), true); }); } /** * Verifies the result of the training operation for a valid unlabeled model Id and training set Url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void beginTrainingUnlabeledResult(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels).getSyncPoller(); syncPoller.waitForCompletion(); validateCustomModelData(syncPoller.getFinalResult(), false); }); } /** * Verifies the result of the copy operation for valid parameters. */ }
```suggestion if (OperationStatus.FAILED.equals(copyResult.getStatus())) { ```
private void throwIfCopyOperationStatusInvalid(CopyOperationResult copyResult) { if (copyResult.getStatus().equals(OperationStatus.FAILED)) { List<ErrorInformation> errorInformationList = copyResult.getCopyResult().getErrors(); if (!CoreUtils.isNullOrEmpty(errorInformationList)) { throw logger.logExceptionAsError(new HttpResponseException("Copy operation returned with a failed " + "status", null, errorInformationList)); } } }
if (copyResult.getStatus().equals(OperationStatus.FAILED)) {
private void throwIfCopyOperationStatusInvalid(CopyOperationResult copyResult) { if (copyResult.getStatus().equals(OperationStatus.FAILED)) { List<ErrorInformation> errorInformationList = copyResult.getCopyResult().getErrors(); if (!CoreUtils.isNullOrEmpty(errorInformationList)) { throw logger.logExceptionAsError(new HttpResponseException("Copy operation returned with a failed " + "status", null, errorInformationList)); } } }
class FormTrainingAsyncClient { private final ClientLogger logger = new ClientLogger(FormTrainingAsyncClient.class); private final FormRecognizerClientImpl service; private final FormRecognizerServiceVersion serviceVersion; /** * Create a {@link FormTrainingClient} that sends requests to the Form Recognizer service's endpoint. * Each service call goes through the {@link FormTrainingClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Form Recognizer supported by this client library. */ FormTrainingAsyncClient(FormRecognizerClientImpl service, FormRecognizerServiceVersion serviceVersion) { this.service = service; this.serviceVersion = serviceVersion; } /** * Creates a new {@link FormRecognizerAsyncClient} object. The new {@link FormTrainingAsyncClient} * uses the same request policy pipeline as the {@link FormTrainingAsyncClient}. * * @return A new {@link FormRecognizerAsyncClient} object. */ public FormRecognizerAsyncClient getFormRecognizerAsyncClient() { return new FormRecognizerClientBuilder().endpoint(getEndpoint()).pipeline(getHttpPipeline()).buildAsyncClient(); } /** * Gets the pipeline the client is using. * * @return the pipeline the client is using. */ HttpPipeline getHttpPipeline() { return service.getHttpPipeline(); } /** * Gets the endpoint the client is using. * * @return the endpoint the client is using. */ String getEndpoint() { return service.getEndpoint(); } /** * Create and train a custom model. * Models are trained using documents that are of the following content type - * 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff'. * Other type of content is ignored. * <p>The service does not support cancellation of the long running operation and returns with an * error message indicating absence of cancellation support.</p> * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginTraining * * @param trainingFilesUrl source URL parameter that is either an externally accessible Azure * storage blob container Uri (preferably a Shared Access Signature Uri). * @param useTrainingLabels Boolean to specify the use of labeled files for training the model. * * @return A {@link PollerFlux} that polls the training model operation until it has completed, has failed, or has * been cancelled. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<OperationResult, CustomFormModel> beginTraining(String trainingFilesUrl, boolean useTrainingLabels) { return beginTraining(trainingFilesUrl, useTrainingLabels, null, null); } /** * Create and train a custom model. * <p>Models are trained using documents that are of the following content type - * 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff'. * Other type of content is ignored. * </p> * <p>The service does not support cancellation of the long running operation and returns with an * error message indicating absence of cancellation support.</p> * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginTraining * * @param trainingFilesUrl an externally accessible Azure storage blob container Uri (preferably a * Shared Access Signature Uri). * @param useTrainingLabels Boolean to specify the use of labeled files for training the model. * @param trainingFileFilter Filter to apply to the documents in the source path for training. * @param pollInterval Duration between each poll for the operation status. If none is specified, a default of * 5 seconds is used. * * @return A {@link PollerFlux} that polls the extract receipt operation until it * has completed, has failed, or has been cancelled. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<OperationResult, CustomFormModel> beginTraining(String trainingFilesUrl, boolean useTrainingLabels, TrainingFileFilter trainingFileFilter, Duration pollInterval) { final Duration interval = pollInterval != null ? pollInterval : DEFAULT_DURATION; return new PollerFlux<OperationResult, CustomFormModel>( interval, getTrainingActivationOperation(trainingFilesUrl, trainingFileFilter != null ? trainingFileFilter.isIncludeSubFolders() : false, trainingFileFilter != null ? trainingFileFilter.getPrefix() : null, useTrainingLabels), createTrainingPollOperation(), (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), fetchTrainingModelResultOperation()); } /** * Get detailed information for a specified custom model id. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCustomModel * * @param modelId The UUID string format model identifier. * * @return The detailed information for the specified model. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CustomFormModel> getCustomModel(String modelId) { return getCustomModelWithResponse(modelId).flatMap(FluxUtil::toMono); } /** * Get detailed information for a specified custom model id with Http response * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCustomModelWithResponse * * @param modelId The UUID string format model identifier. * * @return A {@link Response} containing the requested {@link CustomFormModel model}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CustomFormModel>> getCustomModelWithResponse(String modelId) { try { return withContext(context -> getCustomModelWithResponse(modelId, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<CustomFormModel>> getCustomModelWithResponse(String modelId, Context context) { Objects.requireNonNull(modelId, "'modelId' cannot be null"); return service.getCustomModelWithResponseAsync(UUID.fromString(modelId), true, context) .map(response -> new SimpleResponse<>(response, toCustomFormModel(response.getValue()))); } /** * Get account information for all custom models. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getAccountProperties} * * @return The account information. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AccountProperties> getAccountProperties() { return getAccountPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * Get account information. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getAccountPropertiesWithResponse} * * @return A {@link Response} containing the requested account information details. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AccountProperties>> getAccountPropertiesWithResponse() { try { return withContext(context -> getAccountPropertiesWithResponse(context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<AccountProperties>> getAccountPropertiesWithResponse(Context context) { return service.getCustomModelsWithResponseAsync(context) .map(response -> new SimpleResponse<>(response, new AccountProperties(response.getValue().getSummary().getCount(), response.getValue().getSummary().getLimit()))); } /** * Deletes the specified custom model. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.deleteModel * * @param modelId The UUID string format model identifier. * * @return An empty Mono. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteModel(String modelId) { return deleteModelWithResponse(modelId).flatMap(FluxUtil::toMono); } /** * Deletes the specified custom model. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.deleteModelWithResponse * * @param modelId The UUID string format model identifier. * * @return A {@link Mono} containing containing status code and HTTP headers */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteModelWithResponse(String modelId) { try { return withContext(context -> deleteModelWithResponse(modelId, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> deleteModelWithResponse(String modelId, Context context) { Objects.requireNonNull(modelId, "'modelId' cannot be null"); return service.deleteCustomModelWithResponseAsync(UUID.fromString(modelId), context) .map(response -> new SimpleResponse<>(response, null)); } /** * List information for all models. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.listCustomModels} * * @return {@link PagedFlux} of {@link CustomFormModelInfo}. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<CustomFormModelInfo> listCustomModels() { try { return new PagedFlux<>(() -> withContext(context -> listFirstPageModelInfo(context)), continuationToken -> withContext(context -> listNextPageModelInfo(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } /** * List information for all models with taking {@link Context}. * * @param context Additional context that is passed through the Http pipeline during the service call. * * @return {@link PagedFlux} of {@link CustomFormModelInfo}. */ PagedFlux<CustomFormModelInfo> listCustomModels(Context context) { return new PagedFlux<>(() -> listFirstPageModelInfo(context), continuationToken -> listNextPageModelInfo(continuationToken, context)); } /** * Copy a custom model stored in this resource (the source) to the user specified target Form Recognizer resource. * * <p>This should be called with the source Form Recognizer resource (with the model that is intended to be copied). * The target parameter should be supplied from the target resource's output from * {@link FormTrainingAsyncClient * </p> * * <p>The service does not support cancellation of the long running operation and returns with an * error message indicating absence of cancellation support.</p> * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginCopyModel * * @param modelId Model identifier of the model to copy to the target Form Recognizer resource * @param target the copy authorization to the target Form Recognizer resource. The copy authorization can be * generated from the target resource's call to {@link FormTrainingAsyncClient * * @return A {@link PollerFlux} that polls the copy model operation until it has completed, has failed, * or has been cancelled. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<OperationResult, CustomFormModelInfo> beginCopyModel(String modelId, CopyAuthorization target) { return beginCopyModel(modelId, target, null); } /** * Copy a custom model stored in this resource (the source) to the user specified target Form Recognizer resource. * * <p>This should be called with the source Form Recognizer resource (with the model that is intended to be copied). * The target parameter should be supplied from the target resource's output from * {@link FormTrainingAsyncClient * </p> * * <p>The service does not support cancellation of the long running operation and returns with an * error message indicating absence of cancellation support.</p> * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginCopyModel * * @param modelId Model identifier of the model to copy to the target Form Recognizer resource * @param target the copy authorization to the target Form Recognizer resource. The copy authorization can be * generated from the target resource's call to {@link FormTrainingAsyncClient * @param pollInterval Duration between each poll for the operation status. If none is specified, a default of * 5 seconds is used. * * @return A {@link PollerFlux} that polls the copy model operation until it has completed, has failed, * or has been cancelled. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<OperationResult, CustomFormModelInfo> beginCopyModel(String modelId, CopyAuthorization target, Duration pollInterval) { final Duration interval = pollInterval != null ? pollInterval : DEFAULT_DURATION; return new PollerFlux<OperationResult, CustomFormModelInfo>( interval, getCopyActivationOperation(modelId, target), createCopyPollOperation(modelId), (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), fetchCopyModelResultOperation(modelId, target.getModelId())); } /** * Generate authorization for copying a custom model into the target Form Recognizer resource. * * @param resourceId Azure Resource Id of the target Form Recognizer resource where the model will be copied to. * @param resourceRegion Location of the target Form Recognizer resource. A valid Azure region name supported * by Cognitive Services. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCopyAuthorization * * @return The {@link CopyAuthorization} that could be used to authorize copying model between resources. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CopyAuthorization> getCopyAuthorization(String resourceId, String resourceRegion) { return getCopyAuthorizationWithResponse(resourceId, resourceRegion).flatMap(FluxUtil::toMono); } /** * Generate authorization for copying a custom model into the target Form Recognizer resource. * This should be called by the target resource (where the model will be copied to) and the output can be passed as * the target parameter into {@link FormTrainingAsyncClient * * @param resourceId Azure Resource Id of the target Form Recognizer resource where the model will be copied to. * @param resourceRegion Location of the target Form Recognizer resource. A valid Azure region name supported by * Cognitive Services. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCopyAuthorizationWithResponse * * @return A {@link Response} containing the {@link CopyAuthorization} that could be used to authorize copying * model between resources. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CopyAuthorization>> getCopyAuthorizationWithResponse(String resourceId, String resourceRegion) { try { return withContext(context -> getCopyAuthorizationWithResponse(resourceId, resourceRegion, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<CopyAuthorization>> getCopyAuthorizationWithResponse(String resourceId, String resourceRegion, Context context) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null"); Objects.requireNonNull(resourceRegion, "'resourceRegion' cannot be null"); return service.generateModelCopyAuthorizationWithResponseAsync(context) .map(response -> { CopyAuthorizationResult copyAuthorizationResult = response.getValue(); return new SimpleResponse<>(response, new CopyAuthorization(copyAuthorizationResult.getModelId(), copyAuthorizationResult.getAccessToken(), resourceId, resourceRegion, copyAuthorizationResult.getExpirationDateTimeTicks())); }); } private Mono<PagedResponse<CustomFormModelInfo>> listFirstPageModelInfo(Context context) { return service.listCustomModelsSinglePageAsync(context) .doOnRequest(ignoredValue -> logger.info("Listing information for all models")) .doOnSuccess(response -> logger.info("Listed all models")) .doOnError(error -> logger.warning("Failed to list all models information", error)) .map(res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), toCustomFormModelInfo(res.getValue()), res.getContinuationToken(), null)); } private Mono<PagedResponse<CustomFormModelInfo>> listNextPageModelInfo(String nextPageLink, Context context) { if (CoreUtils.isNullOrEmpty(nextPageLink)) { return Mono.empty(); } return service.listCustomModelsNextSinglePageAsync(nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)) .map(res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), toCustomFormModelInfo(res.getValue()), res.getContinuationToken(), null)); } private Function<PollingContext<OperationResult>, Mono<CustomFormModelInfo>> fetchCopyModelResultOperation( String modelId, String copyModelId) { return (pollingContext) -> { try { final UUID resultUid = UUID.fromString(pollingContext.getLatestResponse().getValue().getResultId()); Objects.requireNonNull(modelId, "'modelId' cannot be null."); return service.getCustomModelCopyResultWithResponseAsync(UUID.fromString(modelId), resultUid) .map(modelSimpleResponse -> { CopyOperationResult copyOperationResult = modelSimpleResponse.getValue(); throwIfCopyOperationStatusInvalid(copyOperationResult); return new CustomFormModelInfo(copyModelId, copyOperationResult.getStatus() == OperationStatus.SUCCEEDED ? CustomFormModelStatus.READY : CustomFormModelStatus.fromString(copyOperationResult.getStatus().toString()), copyOperationResult.getCreatedDateTime(), copyOperationResult.getLastUpdatedDateTime()); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<OperationResult>, Mono<PollResponse<OperationResult>>> createCopyPollOperation(String modelId) { return (pollingContext) -> { try { PollResponse<OperationResult> operationResultPollResponse = pollingContext.getLatestResponse(); UUID targetId = UUID.fromString(operationResultPollResponse.getValue().getResultId()); return service.getCustomModelCopyResultWithResponseAsync(UUID.fromString(modelId), targetId) .flatMap(modelSimpleResponse -> processCopyModelResponse(modelSimpleResponse, operationResultPollResponse)); } catch (HttpResponseException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<OperationResult>, Mono<OperationResult>> getCopyActivationOperation( String modelId, CopyAuthorization target) { return (pollingContext) -> { try { Objects.requireNonNull(modelId, "'modelId' cannot be null."); Objects.requireNonNull(target, "'target' cannot be null."); CopyRequest copyRequest = new CopyRequest() .setTargetResourceId(target.getResourceId()) .setTargetResourceRegion(target.getRegion()) .setCopyAuthorization(new CopyAuthorizationResult() .setModelId(target.getModelId()) .setAccessToken(target.getAccessToken()) .setExpirationDateTimeTicks(target.getExpiresOn())); return service.copyCustomModelWithResponseAsync(UUID.fromString(modelId), copyRequest) .map(response -> new OperationResult(parseModelId(response.getDeserializedHeaders().getOperationLocation()))); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Mono<PollResponse<OperationResult>> processCopyModelResponse( SimpleResponse<CopyOperationResult> copyModel, PollResponse<OperationResult> copyModelOperationResponse) { LongRunningOperationStatus status; switch (copyModel.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case FAILED: status = LongRunningOperationStatus.FAILED; break; default: status = LongRunningOperationStatus.fromString(copyModel.getValue().getStatus().toString(), true); break; } return Mono.just(new PollResponse<>(status, copyModelOperationResponse.getValue())); } private Function<PollingContext<OperationResult>, Mono<CustomFormModel>> fetchTrainingModelResultOperation() { return (pollingContext) -> { try { final UUID modelUid = UUID.fromString(pollingContext.getLatestResponse().getValue().getResultId()); return service.getCustomModelWithResponseAsync(modelUid, true) .map(modelSimpleResponse -> toCustomFormModel(modelSimpleResponse.getValue())); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<OperationResult>, Mono<PollResponse<OperationResult>>> createTrainingPollOperation() { return (pollingContext) -> { try { PollResponse<OperationResult> operationResultPollResponse = pollingContext.getLatestResponse(); UUID modelUid = UUID.fromString(operationResultPollResponse.getValue().getResultId()); return service.getCustomModelWithResponseAsync(modelUid, true) .flatMap(modelSimpleResponse -> processTrainingModelResponse(modelSimpleResponse, operationResultPollResponse)); } catch (HttpResponseException e) { logger.logExceptionAsError(e); return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null)); } }; } private Function<PollingContext<OperationResult>, Mono<OperationResult>> getTrainingActivationOperation( String fileSourceUrl, boolean includeSubFolders, String filePrefix, boolean useTrainingLabels) { return (pollingContext) -> { try { Objects.requireNonNull(fileSourceUrl, "'fileSourceUrl' cannot be null."); TrainSourceFilter trainSourceFilter = new TrainSourceFilter().setIncludeSubFolders(includeSubFolders) .setPrefix(filePrefix); TrainRequest serviceTrainRequest = new TrainRequest().setSource(fileSourceUrl). setSourceFilter(trainSourceFilter).setUseLabelFile(useTrainingLabels); return service.trainCustomModelAsyncWithResponseAsync(serviceTrainRequest) .map(response -> new OperationResult(parseModelId(response.getDeserializedHeaders().getLocation()))); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private static Mono<PollResponse<OperationResult>> processTrainingModelResponse( SimpleResponse<Model> trainingModel, PollResponse<OperationResult> trainingModelOperationResponse) { LongRunningOperationStatus status; switch (trainingModel.getValue().getModelInfo().getStatus()) { case CREATING: status = LongRunningOperationStatus.IN_PROGRESS; break; case READY: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case INVALID: status = LongRunningOperationStatus.FAILED; break; default: status = LongRunningOperationStatus.fromString( trainingModel.getValue().getModelInfo().getStatus().toString(), true); break; } return Mono.just(new PollResponse<>(status, trainingModelOperationResponse.getValue())); } /** * Helper method that throws a {@link HttpResponseException} if {@link CopyOperationResult * {@link OperationStatus * * @param copyResult The copy operation response returned from the service. */ }
class FormTrainingAsyncClient { private final ClientLogger logger = new ClientLogger(FormTrainingAsyncClient.class); private final FormRecognizerClientImpl service; private final FormRecognizerServiceVersion serviceVersion; /** * Create a {@link FormTrainingClient} that sends requests to the Form Recognizer service's endpoint. * Each service call goes through the {@link FormTrainingClientBuilder * * @param service The proxy service used to perform REST calls. * @param serviceVersion The versions of Azure Form Recognizer supported by this client library. */ FormTrainingAsyncClient(FormRecognizerClientImpl service, FormRecognizerServiceVersion serviceVersion) { this.service = service; this.serviceVersion = serviceVersion; } /** * Creates a new {@link FormRecognizerAsyncClient} object. The new {@link FormTrainingAsyncClient} * uses the same request policy pipeline as the {@link FormTrainingAsyncClient}. * * @return A new {@link FormRecognizerAsyncClient} object. */ public FormRecognizerAsyncClient getFormRecognizerAsyncClient() { return new FormRecognizerClientBuilder().endpoint(getEndpoint()).pipeline(getHttpPipeline()).buildAsyncClient(); } /** * Gets the pipeline the client is using. * * @return the pipeline the client is using. */ HttpPipeline getHttpPipeline() { return service.getHttpPipeline(); } /** * Gets the endpoint the client is using. * * @return the endpoint the client is using. */ String getEndpoint() { return service.getEndpoint(); } /** * Create and train a custom model. * Models are trained using documents that are of the following content type - * 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff'. * Other type of content is ignored. * <p>The service does not support cancellation of the long running operation and returns with an * error message indicating absence of cancellation support.</p> * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginTraining * * @param trainingFilesUrl source URL parameter that is either an externally accessible Azure * storage blob container Uri (preferably a Shared Access Signature Uri). * @param useTrainingLabels Boolean to specify the use of labeled files for training the model. * * @return A {@link PollerFlux} that polls the training model operation until it has completed, has failed, or has * been cancelled. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<OperationResult, CustomFormModel> beginTraining(String trainingFilesUrl, boolean useTrainingLabels) { return beginTraining(trainingFilesUrl, useTrainingLabels, null, null); } /** * Create and train a custom model. * <p>Models are trained using documents that are of the following content type - * 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff'. * Other type of content is ignored. * </p> * <p>The service does not support cancellation of the long running operation and returns with an * error message indicating absence of cancellation support.</p> * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginTraining * * @param trainingFilesUrl an externally accessible Azure storage blob container Uri (preferably a * Shared Access Signature Uri). * @param useTrainingLabels Boolean to specify the use of labeled files for training the model. * @param trainingFileFilter Filter to apply to the documents in the source path for training. * @param pollInterval Duration between each poll for the operation status. If none is specified, a default of * 5 seconds is used. * * @return A {@link PollerFlux} that polls the extract receipt operation until it * has completed, has failed, or has been cancelled. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<OperationResult, CustomFormModel> beginTraining(String trainingFilesUrl, boolean useTrainingLabels, TrainingFileFilter trainingFileFilter, Duration pollInterval) { final Duration interval = pollInterval != null ? pollInterval : DEFAULT_DURATION; return new PollerFlux<OperationResult, CustomFormModel>( interval, getTrainingActivationOperation(trainingFilesUrl, trainingFileFilter != null ? trainingFileFilter.isIncludeSubFolders() : false, trainingFileFilter != null ? trainingFileFilter.getPrefix() : null, useTrainingLabels), createTrainingPollOperation(), (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), fetchTrainingModelResultOperation()); } /** * Get detailed information for a specified custom model id. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCustomModel * * @param modelId The UUID string format model identifier. * * @return The detailed information for the specified model. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CustomFormModel> getCustomModel(String modelId) { return getCustomModelWithResponse(modelId).flatMap(FluxUtil::toMono); } /** * Get detailed information for a specified custom model id with Http response * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCustomModelWithResponse * * @param modelId The UUID string format model identifier. * * @return A {@link Response} containing the requested {@link CustomFormModel model}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CustomFormModel>> getCustomModelWithResponse(String modelId) { try { return withContext(context -> getCustomModelWithResponse(modelId, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<CustomFormModel>> getCustomModelWithResponse(String modelId, Context context) { Objects.requireNonNull(modelId, "'modelId' cannot be null"); return service.getCustomModelWithResponseAsync(UUID.fromString(modelId), true, context) .map(response -> new SimpleResponse<>(response, toCustomFormModel(response.getValue()))); } /** * Get account information for all custom models. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getAccountProperties} * * @return The account information. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AccountProperties> getAccountProperties() { return getAccountPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * Get account information. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getAccountPropertiesWithResponse} * * @return A {@link Response} containing the requested account information details. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AccountProperties>> getAccountPropertiesWithResponse() { try { return withContext(context -> getAccountPropertiesWithResponse(context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<AccountProperties>> getAccountPropertiesWithResponse(Context context) { return service.getCustomModelsWithResponseAsync(context) .map(response -> new SimpleResponse<>(response, new AccountProperties(response.getValue().getSummary().getCount(), response.getValue().getSummary().getLimit()))); } /** * Deletes the specified custom model. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.deleteModel * * @param modelId The UUID string format model identifier. * * @return An empty Mono. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteModel(String modelId) { return deleteModelWithResponse(modelId).flatMap(FluxUtil::toMono); } /** * Deletes the specified custom model. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.deleteModelWithResponse * * @param modelId The UUID string format model identifier. * * @return A {@link Mono} containing containing status code and HTTP headers */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteModelWithResponse(String modelId) { try { return withContext(context -> deleteModelWithResponse(modelId, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> deleteModelWithResponse(String modelId, Context context) { Objects.requireNonNull(modelId, "'modelId' cannot be null"); return service.deleteCustomModelWithResponseAsync(UUID.fromString(modelId), context) .map(response -> new SimpleResponse<>(response, null)); } /** * List information for all models. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.listCustomModels} * * @return {@link PagedFlux} of {@link CustomFormModelInfo}. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<CustomFormModelInfo> listCustomModels() { try { return new PagedFlux<>(() -> withContext(context -> listFirstPageModelInfo(context)), continuationToken -> withContext(context -> listNextPageModelInfo(continuationToken, context))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } } /** * List information for all models with taking {@link Context}. * * @param context Additional context that is passed through the Http pipeline during the service call. * * @return {@link PagedFlux} of {@link CustomFormModelInfo}. */ PagedFlux<CustomFormModelInfo> listCustomModels(Context context) { return new PagedFlux<>(() -> listFirstPageModelInfo(context), continuationToken -> listNextPageModelInfo(continuationToken, context)); } /** * Copy a custom model stored in this resource (the source) to the user specified target Form Recognizer resource. * * <p>This should be called with the source Form Recognizer resource (with the model that is intended to be copied). * The target parameter should be supplied from the target resource's output from * {@link FormTrainingAsyncClient * </p> * * <p>The service does not support cancellation of the long running operation and returns with an * error message indicating absence of cancellation support.</p> * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginCopyModel * * @param modelId Model identifier of the model to copy to the target Form Recognizer resource * @param target the copy authorization to the target Form Recognizer resource. The copy authorization can be * generated from the target resource's call to {@link FormTrainingAsyncClient * * @return A {@link PollerFlux} that polls the copy model operation until it has completed, has failed, * or has been cancelled. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<OperationResult, CustomFormModelInfo> beginCopyModel(String modelId, CopyAuthorization target) { return beginCopyModel(modelId, target, null); } /** * Copy a custom model stored in this resource (the source) to the user specified target Form Recognizer resource. * * <p>This should be called with the source Form Recognizer resource (with the model that is intended to be copied). * The target parameter should be supplied from the target resource's output from * {@link FormTrainingAsyncClient * </p> * * <p>The service does not support cancellation of the long running operation and returns with an * error message indicating absence of cancellation support.</p> * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginCopyModel * * @param modelId Model identifier of the model to copy to the target Form Recognizer resource * @param target the copy authorization to the target Form Recognizer resource. The copy authorization can be * generated from the target resource's call to {@link FormTrainingAsyncClient * @param pollInterval Duration between each poll for the operation status. If none is specified, a default of * 5 seconds is used. * * @return A {@link PollerFlux} that polls the copy model operation until it has completed, has failed, * or has been cancelled. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<OperationResult, CustomFormModelInfo> beginCopyModel(String modelId, CopyAuthorization target, Duration pollInterval) { final Duration interval = pollInterval != null ? pollInterval : DEFAULT_DURATION; return new PollerFlux<OperationResult, CustomFormModelInfo>( interval, getCopyActivationOperation(modelId, target), createCopyPollOperation(modelId), (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), fetchCopyModelResultOperation(modelId, target.getModelId())); } /** * Generate authorization for copying a custom model into the target Form Recognizer resource. * * @param resourceId Azure Resource Id of the target Form Recognizer resource where the model will be copied to. * @param resourceRegion Location of the target Form Recognizer resource. A valid Azure region name supported * by Cognitive Services. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCopyAuthorization * * @return The {@link CopyAuthorization} that could be used to authorize copying model between resources. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CopyAuthorization> getCopyAuthorization(String resourceId, String resourceRegion) { return getCopyAuthorizationWithResponse(resourceId, resourceRegion).flatMap(FluxUtil::toMono); } /** * Generate authorization for copying a custom model into the target Form Recognizer resource. * This should be called by the target resource (where the model will be copied to) and the output can be passed as * the target parameter into {@link FormTrainingAsyncClient * * @param resourceId Azure Resource Id of the target Form Recognizer resource where the model will be copied to. * @param resourceRegion Location of the target Form Recognizer resource. A valid Azure region name supported by * Cognitive Services. * * <p><strong>Code sample</strong></p> * {@codesnippet com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.getCopyAuthorizationWithResponse * * @return A {@link Response} containing the {@link CopyAuthorization} that could be used to authorize copying * model between resources. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CopyAuthorization>> getCopyAuthorizationWithResponse(String resourceId, String resourceRegion) { try { return withContext(context -> getCopyAuthorizationWithResponse(resourceId, resourceRegion, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<CopyAuthorization>> getCopyAuthorizationWithResponse(String resourceId, String resourceRegion, Context context) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null"); Objects.requireNonNull(resourceRegion, "'resourceRegion' cannot be null"); return service.generateModelCopyAuthorizationWithResponseAsync(context) .map(response -> { CopyAuthorizationResult copyAuthorizationResult = response.getValue(); return new SimpleResponse<>(response, new CopyAuthorization(copyAuthorizationResult.getModelId(), copyAuthorizationResult.getAccessToken(), resourceId, resourceRegion, copyAuthorizationResult.getExpirationDateTimeTicks())); }); } private Mono<PagedResponse<CustomFormModelInfo>> listFirstPageModelInfo(Context context) { return service.listCustomModelsSinglePageAsync(context) .doOnRequest(ignoredValue -> logger.info("Listing information for all models")) .doOnSuccess(response -> logger.info("Listed all models")) .doOnError(error -> logger.warning("Failed to list all models information", error)) .map(res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), toCustomFormModelInfo(res.getValue()), res.getContinuationToken(), null)); } private Mono<PagedResponse<CustomFormModelInfo>> listNextPageModelInfo(String nextPageLink, Context context) { if (CoreUtils.isNullOrEmpty(nextPageLink)) { return Mono.empty(); } return service.listCustomModelsNextSinglePageAsync(nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)) .map(res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), toCustomFormModelInfo(res.getValue()), res.getContinuationToken(), null)); } private Function<PollingContext<OperationResult>, Mono<CustomFormModelInfo>> fetchCopyModelResultOperation( String modelId, String copyModelId) { return (pollingContext) -> { try { final UUID resultUid = UUID.fromString(pollingContext.getLatestResponse().getValue().getResultId()); Objects.requireNonNull(modelId, "'modelId' cannot be null."); return service.getCustomModelCopyResultWithResponseAsync(UUID.fromString(modelId), resultUid) .map(modelSimpleResponse -> { CopyOperationResult copyOperationResult = modelSimpleResponse.getValue(); throwIfCopyOperationStatusInvalid(copyOperationResult); return new CustomFormModelInfo(copyModelId, copyOperationResult.getStatus() == OperationStatus.SUCCEEDED ? CustomFormModelStatus.READY : CustomFormModelStatus.fromString(copyOperationResult.getStatus().toString()), copyOperationResult.getCreatedDateTime(), copyOperationResult.getLastUpdatedDateTime()); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<OperationResult>, Mono<PollResponse<OperationResult>>> createCopyPollOperation(String modelId) { return (pollingContext) -> { try { PollResponse<OperationResult> operationResultPollResponse = pollingContext.getLatestResponse(); UUID targetId = UUID.fromString(operationResultPollResponse.getValue().getResultId()); return service.getCustomModelCopyResultWithResponseAsync(UUID.fromString(modelId), targetId) .flatMap(modelSimpleResponse -> processCopyModelResponse(modelSimpleResponse, operationResultPollResponse)); } catch (HttpResponseException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<OperationResult>, Mono<OperationResult>> getCopyActivationOperation( String modelId, CopyAuthorization target) { return (pollingContext) -> { try { Objects.requireNonNull(modelId, "'modelId' cannot be null."); Objects.requireNonNull(target, "'target' cannot be null."); CopyRequest copyRequest = new CopyRequest() .setTargetResourceId(target.getResourceId()) .setTargetResourceRegion(target.getResourceRegion()) .setCopyAuthorization(new CopyAuthorizationResult() .setModelId(target.getModelId()) .setAccessToken(target.getAccessToken()) .setExpirationDateTimeTicks(target.getExpiresOn())); return service.copyCustomModelWithResponseAsync(UUID.fromString(modelId), copyRequest) .map(response -> new OperationResult(parseModelId(response.getDeserializedHeaders().getOperationLocation()))); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Mono<PollResponse<OperationResult>> processCopyModelResponse( SimpleResponse<CopyOperationResult> copyModel, PollResponse<OperationResult> copyModelOperationResponse) { LongRunningOperationStatus status; switch (copyModel.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case FAILED: status = LongRunningOperationStatus.FAILED; break; default: status = LongRunningOperationStatus.fromString(copyModel.getValue().getStatus().toString(), true); break; } return Mono.just(new PollResponse<>(status, copyModelOperationResponse.getValue())); } private Function<PollingContext<OperationResult>, Mono<CustomFormModel>> fetchTrainingModelResultOperation() { return (pollingContext) -> { try { final UUID modelUid = UUID.fromString(pollingContext.getLatestResponse().getValue().getResultId()); return service.getCustomModelWithResponseAsync(modelUid, true) .map(modelSimpleResponse -> toCustomFormModel(modelSimpleResponse.getValue())); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<OperationResult>, Mono<PollResponse<OperationResult>>> createTrainingPollOperation() { return (pollingContext) -> { try { PollResponse<OperationResult> operationResultPollResponse = pollingContext.getLatestResponse(); UUID modelUid = UUID.fromString(operationResultPollResponse.getValue().getResultId()); return service.getCustomModelWithResponseAsync(modelUid, true) .flatMap(modelSimpleResponse -> processTrainingModelResponse(modelSimpleResponse, operationResultPollResponse)); } catch (HttpResponseException e) { logger.logExceptionAsError(e); return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null)); } }; } private Function<PollingContext<OperationResult>, Mono<OperationResult>> getTrainingActivationOperation( String fileSourceUrl, boolean includeSubFolders, String filePrefix, boolean useTrainingLabels) { return (pollingContext) -> { try { Objects.requireNonNull(fileSourceUrl, "'fileSourceUrl' cannot be null."); TrainSourceFilter trainSourceFilter = new TrainSourceFilter().setIncludeSubFolders(includeSubFolders) .setPrefix(filePrefix); TrainRequest serviceTrainRequest = new TrainRequest().setSource(fileSourceUrl). setSourceFilter(trainSourceFilter).setUseLabelFile(useTrainingLabels); return service.trainCustomModelAsyncWithResponseAsync(serviceTrainRequest) .map(response -> new OperationResult(parseModelId(response.getDeserializedHeaders().getLocation()))); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private static Mono<PollResponse<OperationResult>> processTrainingModelResponse( SimpleResponse<Model> trainingModel, PollResponse<OperationResult> trainingModelOperationResponse) { LongRunningOperationStatus status; switch (trainingModel.getValue().getModelInfo().getStatus()) { case CREATING: status = LongRunningOperationStatus.IN_PROGRESS; break; case READY: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case INVALID: status = LongRunningOperationStatus.FAILED; break; default: status = LongRunningOperationStatus.fromString( trainingModel.getValue().getModelInfo().getStatus().toString(), true); break; } return Mono.just(new PollResponse<>(status, trainingModelOperationResponse.getValue())); } /** * Helper method that throws a {@link HttpResponseException} if {@link CopyOperationResult * {@link OperationStatus * * @param copyResult The copy operation response returned from the service. */ }
nit: we don't need `this` keyword here.
public String getModelId() { return this.modelId; }
return this.modelId;
public String getModelId() { return this.modelId; }
class CopyAuthorization { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); CopyAuthorization() { super(); } /* * Model identifier. */ private String modelId; /* * Token claim used to authorize the request. */ private String accessToken; /* * Resource Identifier. */ @JsonIgnore private String resourceId; /* * Region of the resource. */ @JsonIgnore private String region; /* * The time when the access token expires. The date is represented as the * number of seconds from 1970-01-01T0:0:0Z UTC until the expiration time. */ @JsonProperty("expirationDateTimeTicks") private long expiresOn; /** * Create a CopyAuthorization object * * @param modelId The model identifier * @param accessToken The token used to authorize the request * @param resourceId The resource identifier * @param region The region of the resource * @param expiresOn The expiry time of the token */ public CopyAuthorization(final String modelId, final String accessToken, final String resourceId, final String region, final long expiresOn) { this.modelId = modelId; this.accessToken = accessToken; this.resourceId = resourceId; this.region = region; this.expiresOn = expiresOn; } /** * Get the modelId property. * * @return the {@code modelId} value. */ /** * Get the token claim used to authorize the request. * * @return the {@code accessToken} value. */ public String getAccessToken() { return this.accessToken; } /** * Get the time when the access token expires. The date is represented as the * number of seconds from 1970-01-01T0:0:0Z UTC until the expiration time. * * @return the {@code expiresOn} value. */ public long getExpiresOn() { return this.expiresOn; } /** * Get the Azure Resource Id of the target Form Recognizer resource * where the model will be copied to. * * @return the {@code resourceId} value. */ public String getResourceId() { return resourceId; } /** * Get the location of the target Form Recognizer resource. * * @return the {@code resourceRegion} value. */ public String getRegion() { return region; } /** * Converts the CopyAuthorization object to its equivalent json string representation. * * @return the json string representation of the CopyAuthorization object. * @throws IOException exception from serialization */ public String toJson() throws IOException { return SERIALIZER.serialize(this, SerializerEncoding.JSON); } /** * Converts the json string representation to its equivalent CopyAuthorization object. * * @param copyAuthorization the json string representation of the object. * * @return the CopyAuthorization object equivalent of the json string. * @throws IOException exception from deserialization */ public static CopyAuthorization fromJson(String copyAuthorization) throws IOException { return SERIALIZER.deserialize(copyAuthorization, CopyAuthorization.class, SerializerEncoding.JSON); } /** * Set the Model identifier. * * @param modelId the modelId value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setModelId(final String modelId) { this.modelId = modelId; return this; } /** * Set the token claim used to authorize the request. * * @param accessToken the token value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setAccessToken(final String accessToken) { this.accessToken = accessToken; return this; } /** * Set the resource Identifier. * * @param resourceId the resourceId value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setResourceId(final String resourceId) { this.resourceId = resourceId; return this; } /** * Set the region of the resource. * * @param region the region value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setRegion(final String region) { this.region = region; return this; } /** * Set the time when the access token expires. * * @param expiresOn the expiresOn value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setExpiresOn(final long expiresOn) { this.expiresOn = expiresOn; return this; } }
class CopyAuthorization { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); CopyAuthorization() { super(); } /* * Model identifier. */ private String modelId; /* * Token claim used to authorize the request. */ private String accessToken; /* * Resource Identifier. */ private String resourceId; /* * Region of the resource. */ private String resourceRegion; /* * The time when the access token expires. The date is represented as the * number of seconds from 1970-01-01T0:0:0Z UTC until the expiration time. */ @JsonProperty("expirationDateTimeTicks") private long expiresOn; /** * Create a CopyAuthorization object * * @param modelId The model identifier * @param accessToken The token used to authorize the request * @param resourceId The resource identifier * @param resourceRegion The region of the resource * @param expiresOn The expiry time of the token */ public CopyAuthorization(final String modelId, final String accessToken, final String resourceId, final String resourceRegion, final long expiresOn) { this.modelId = modelId; this.accessToken = accessToken; this.resourceId = resourceId; this.resourceRegion = resourceRegion; this.expiresOn = expiresOn; } /** * Get the modelId property. * * @return the {@code modelId} value. */ /** * Get the token claim used to authorize the request. * * @return the {@code accessToken} value. */ public String getAccessToken() { return this.accessToken; } /** * Get the time when the access token expires. The date is represented as the * number of seconds from 1970-01-01T0:0:0Z UTC until the expiration time. * * @return the {@code expiresOn} value. */ public long getExpiresOn() { return this.expiresOn; } /** * Get the Azure Resource Id of the target Form Recognizer resource * where the model will be copied to. * * @return the {@code resourceId} value. */ public String getResourceId() { return resourceId; } /** * Get the location of the target Form Recognizer resource. * * @return the {@code resourceRegion} value. */ public String getResourceRegion() { return resourceRegion; } /** * Converts the CopyAuthorization object to its equivalent json string representation. * * @return the json string representation of the CopyAuthorization object. * @throws IOException exception from serialization */ public String toJson() throws IOException { return SERIALIZER.serialize(this, SerializerEncoding.JSON); } /** * Converts the json string representation to its equivalent CopyAuthorization object. * * @param copyAuthorization the json string representation of the object. * * @return the CopyAuthorization object equivalent of the json string. * @throws IOException exception from deserialization */ public static CopyAuthorization fromJson(String copyAuthorization) throws IOException { return SERIALIZER.deserialize(copyAuthorization, CopyAuthorization.class, SerializerEncoding.JSON); } /** * Set the Model identifier. * * @param modelId the modelId value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setModelId(final String modelId) { this.modelId = modelId; return this; } /** * Set the token claim used to authorize the request. * * @param accessToken the token value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setAccessToken(final String accessToken) { this.accessToken = accessToken; return this; } /** * Set the resource Identifier. * * @param resourceId the resourceId value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setResourceId(final String resourceId) { this.resourceId = resourceId; return this; } /** * Set the region of the resource. * * @param resourceRegion the region value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setResourceRegion(final String resourceRegion) { this.resourceRegion = resourceRegion; return this; } /** * Set the time when the access token expires. * * @param expiresOn the expiresOn value to set. * * @return the CopyAuthorization object itself. */ public CopyAuthorization setExpiresOn(final long expiresOn) { this.expiresOn = expiresOn; return this; } }
Wow, that was a bug? Is PKrangeID always guaranteed in this code path?
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
this is for validation. Why this change is needed?
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
Yes, this was a bug. It is guaranteed, if not present, then it is a bug.
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
log and throw
public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(new AuthenticationRequiredException("Authenticating in this environment requires" + " specifying a TokenRequestContext.")); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); }
}
public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException("Authenticating in this " + "environment requires specifying a TokenRequestContext."))); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); }
class DeviceCodeCredential implements TokenCredential { private final Consumer<DeviceCodeInfo> challengeConsumer; private final IdentityClient identityClient; private final AtomicReference<MsalAuthenticationAccount> cachedToken; private final String authorityHost; private final boolean automaticAuthentication; /** * Creates a DeviceCodeCredential with the given identity client options. * * @param clientId the client ID of the application * @param tenantId the tenant ID of the application * @param challengeConsumer a method allowing the user to meet the device code challenge * @param identityClientOptions the options for configuring the identity client */ DeviceCodeCredential(String clientId, String tenantId, Consumer<DeviceCodeInfo> challengeConsumer, boolean automaticAuthentication, IdentityClientOptions identityClientOptions) { this.challengeConsumer = challengeConsumer; identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); this.cachedToken = new AtomicReference<>(); this.authorityHost = identityClientOptions.getAuthorityHost(); this.automaticAuthentication = automaticAuthentication; if (identityClientOptions.getAuthenticationRecord() != null) { cachedToken.set(new MsalAuthenticationAccount(identityClientOptions.getAuthenticationRecord())); } } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithMsalAccount(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(new AuthenticationRequiredException("Interactive authentication is needed to " + "acquire token. Call Authenticate to initiate the device code authentication.")); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); } /** * Interactively authenticates a user via the default browser. * * @param request The details of the authentication request. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate(TokenRequestContext request) { return Mono.defer(() -> identityClient.authenticateWithDeviceCode(request, challengeConsumer)) .map(msalToken -> new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId())); } /** * Interactively authenticates a user via the default browser. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ }
class DeviceCodeCredential implements TokenCredential { private final Consumer<DeviceCodeInfo> challengeConsumer; private final IdentityClient identityClient; private final AtomicReference<MsalAuthenticationAccount> cachedToken; private final String authorityHost; private final boolean automaticAuthentication; private final ClientLogger logger = new ClientLogger(DeviceCodeCredential.class); /** * Creates a DeviceCodeCredential with the given identity client options. * * @param clientId the client ID of the application * @param tenantId the tenant ID of the application * @param challengeConsumer a method allowing the user to meet the device code challenge * @param automaticAuthentication indicates whether automatic authentication should be attempted or not. * @param identityClientOptions the options for configuring the identity client */ DeviceCodeCredential(String clientId, String tenantId, Consumer<DeviceCodeInfo> challengeConsumer, boolean automaticAuthentication, IdentityClientOptions identityClientOptions) { this.challengeConsumer = challengeConsumer; identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); this.cachedToken = new AtomicReference<>(); this.authorityHost = identityClientOptions.getAuthorityHost(); this.automaticAuthentication = automaticAuthentication; if (identityClientOptions.getAuthenticationRecord() != null) { cachedToken.set(new MsalAuthenticationAccount(identityClientOptions.getAuthenticationRecord())); } } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithPublicClientCache(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(logger.logExceptionAsError(new AuthenticationRequiredException("Interactive " + "authentication is needed to acquire token. Call Authenticate to initiate the device " + "code authentication.", request))); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); } /** * Authenticates a user via the device code flow. * * <p> The credential acquires a verification URL and code from the Azure Active Directory. The user must * browse to the URL, enter the code, and authenticate with Azure Active Directory. If the user authenticates * successfully, the credential receives an access token. </p> * * @param request The details of the authentication request. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate(TokenRequestContext request) { return Mono.defer(() -> identityClient.authenticateWithDeviceCode(request, challengeConsumer)) .map(msalToken -> new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId())); } /** * Authenticates a user via the device code flow. * * <p> The credential acquires a verification URL and code from the Azure Active Directory. The user must * browse to the URL, enter the code, and authenticate with Azure Active Directory. If the user authenticates * successfully, the credential receives an access token. </p> * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ }
please add a unit test for the change. See `PartitionKeyInternalTest` for existing tests.
public void serialize(PartitionKeyInternal partitionKey, JsonGenerator writer, SerializerProvider serializerProvider) { try { if (partitionKey.equals(PartitionKeyInternal.getExclusiveMaximum())) { writer.writeString(INFINITY); return; } if (partitionKey.getComponents() != null) { writer.writeStartArray(); for (IPartitionKeyComponent componentValue : partitionKey.getComponents()) { componentValue.jsonEncode(writer); } writer.writeEndArray(); } } catch (IOException e) { throw new IllegalStateException(e); } }
writer.writeEndArray();
public void serialize(PartitionKeyInternal partitionKey, JsonGenerator writer, SerializerProvider serializerProvider) { try { if (partitionKey.equals(PartitionKeyInternal.getExclusiveMaximum())) { writer.writeString(INFINITY); return; } if (partitionKey.getComponents() != null) { writer.writeStartArray(); for (IPartitionKeyComponent componentValue : partitionKey.getComponents()) { componentValue.jsonEncode(writer); } writer.writeEndArray(); } } catch (IOException e) { throw new IllegalStateException(e); } }
class PartitionKeyInternalJsonSerializer extends StdSerializer<PartitionKeyInternal> { private static final long serialVersionUID = 2258093043805843865L; protected PartitionKeyInternalJsonSerializer() { this(null); } protected PartitionKeyInternalJsonSerializer(Class<PartitionKeyInternal> t) { super(t); } @Override static void jsonEncode(MinNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_NUMBER); } static void jsonEncode(MaxNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_NUMBER); } static void jsonEncode(MinStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_STRING); } static void jsonEncode(MaxStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_STRING); } private static void jsonEncodeLimit(JsonGenerator writer, String value) { try { writer.writeStartObject(); writer.writeFieldName(TYPE); writer.writeString(value); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } }
class PartitionKeyInternalJsonSerializer extends StdSerializer<PartitionKeyInternal> { private static final long serialVersionUID = 2258093043805843865L; protected PartitionKeyInternalJsonSerializer() { this(null); } protected PartitionKeyInternalJsonSerializer(Class<PartitionKeyInternal> t) { super(t); } @Override static void jsonEncode(MinNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_NUMBER); } static void jsonEncode(MaxNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_NUMBER); } static void jsonEncode(MinStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_STRING); } static void jsonEncode(MaxStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_STRING); } private static void jsonEncodeLimit(JsonGenerator writer, String value) { try { writer.writeStartObject(); writer.writeFieldName(TYPE); writer.writeString(value); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } }
This code path will always throw IllegalStateException - because we are always passing empty string - here is the issue - https://github.com/Azure/azure-sdk-for-java/issues/9053
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
Sure, will do.
public void serialize(PartitionKeyInternal partitionKey, JsonGenerator writer, SerializerProvider serializerProvider) { try { if (partitionKey.equals(PartitionKeyInternal.getExclusiveMaximum())) { writer.writeString(INFINITY); return; } if (partitionKey.getComponents() != null) { writer.writeStartArray(); for (IPartitionKeyComponent componentValue : partitionKey.getComponents()) { componentValue.jsonEncode(writer); } writer.writeEndArray(); } } catch (IOException e) { throw new IllegalStateException(e); } }
writer.writeEndArray();
public void serialize(PartitionKeyInternal partitionKey, JsonGenerator writer, SerializerProvider serializerProvider) { try { if (partitionKey.equals(PartitionKeyInternal.getExclusiveMaximum())) { writer.writeString(INFINITY); return; } if (partitionKey.getComponents() != null) { writer.writeStartArray(); for (IPartitionKeyComponent componentValue : partitionKey.getComponents()) { componentValue.jsonEncode(writer); } writer.writeEndArray(); } } catch (IOException e) { throw new IllegalStateException(e); } }
class PartitionKeyInternalJsonSerializer extends StdSerializer<PartitionKeyInternal> { private static final long serialVersionUID = 2258093043805843865L; protected PartitionKeyInternalJsonSerializer() { this(null); } protected PartitionKeyInternalJsonSerializer(Class<PartitionKeyInternal> t) { super(t); } @Override static void jsonEncode(MinNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_NUMBER); } static void jsonEncode(MaxNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_NUMBER); } static void jsonEncode(MinStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_STRING); } static void jsonEncode(MaxStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_STRING); } private static void jsonEncodeLimit(JsonGenerator writer, String value) { try { writer.writeStartObject(); writer.writeFieldName(TYPE); writer.writeString(value); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } }
class PartitionKeyInternalJsonSerializer extends StdSerializer<PartitionKeyInternal> { private static final long serialVersionUID = 2258093043805843865L; protected PartitionKeyInternalJsonSerializer() { this(null); } protected PartitionKeyInternalJsonSerializer(Class<PartitionKeyInternal> t) { super(t); } @Override static void jsonEncode(MinNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_NUMBER); } static void jsonEncode(MaxNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_NUMBER); } static void jsonEncode(MinStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_STRING); } static void jsonEncode(MaxStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_STRING); } private static void jsonEncodeLimit(JsonGenerator writer, String value) { try { writer.writeStartObject(); writer.writeFieldName(TYPE); writer.writeString(value); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } }
@kushagraThapar https://github.com/Azure/azure-sdk-for-java/issues/9053 is for the PartitionKey.None is that right link?
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
Yes, my bad. Here is the right link - https://github.com/Azure/azure-sdk-for-java/issues/10493
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
Added unit test.
public void serialize(PartitionKeyInternal partitionKey, JsonGenerator writer, SerializerProvider serializerProvider) { try { if (partitionKey.equals(PartitionKeyInternal.getExclusiveMaximum())) { writer.writeString(INFINITY); return; } if (partitionKey.getComponents() != null) { writer.writeStartArray(); for (IPartitionKeyComponent componentValue : partitionKey.getComponents()) { componentValue.jsonEncode(writer); } writer.writeEndArray(); } } catch (IOException e) { throw new IllegalStateException(e); } }
writer.writeEndArray();
public void serialize(PartitionKeyInternal partitionKey, JsonGenerator writer, SerializerProvider serializerProvider) { try { if (partitionKey.equals(PartitionKeyInternal.getExclusiveMaximum())) { writer.writeString(INFINITY); return; } if (partitionKey.getComponents() != null) { writer.writeStartArray(); for (IPartitionKeyComponent componentValue : partitionKey.getComponents()) { componentValue.jsonEncode(writer); } writer.writeEndArray(); } } catch (IOException e) { throw new IllegalStateException(e); } }
class PartitionKeyInternalJsonSerializer extends StdSerializer<PartitionKeyInternal> { private static final long serialVersionUID = 2258093043805843865L; protected PartitionKeyInternalJsonSerializer() { this(null); } protected PartitionKeyInternalJsonSerializer(Class<PartitionKeyInternal> t) { super(t); } @Override static void jsonEncode(MinNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_NUMBER); } static void jsonEncode(MaxNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_NUMBER); } static void jsonEncode(MinStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_STRING); } static void jsonEncode(MaxStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_STRING); } private static void jsonEncodeLimit(JsonGenerator writer, String value) { try { writer.writeStartObject(); writer.writeFieldName(TYPE); writer.writeString(value); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } }
class PartitionKeyInternalJsonSerializer extends StdSerializer<PartitionKeyInternal> { private static final long serialVersionUID = 2258093043805843865L; protected PartitionKeyInternalJsonSerializer() { this(null); } protected PartitionKeyInternalJsonSerializer(Class<PartitionKeyInternal> t) { super(t); } @Override static void jsonEncode(MinNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_NUMBER); } static void jsonEncode(MaxNumberPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_NUMBER); } static void jsonEncode(MinStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MIN_STRING); } static void jsonEncode(MaxStringPartitionKeyComponent component, JsonGenerator writer) { jsonEncodeLimit(writer, MAX_STRING); } private static void jsonEncodeLimit(JsonGenerator writer, String value) { try { writer.writeStartObject(); writer.writeFieldName(TYPE); writer.writeString(value); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } }
@kirankumarkolli @kushagraThapar .Net seem to be doing the same thing as we used to do here: SessionTokenHelper.cs: ```java public static void ValidateAndRemoveSessionToken(DocumentServiceRequest request) { string sessionToken = request.Headers[HttpConstants.HttpHeaders.SessionToken]; if (!string.IsNullOrEmpty(sessionToken)) { GetLocalSessionToken(request, sessionToken, string.Empty); request.Headers.Remove(HttpConstants.HttpHeaders.SessionToken); } } ```
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
True, but .Net doesn't throw Exception on passing empty partition key range id. Like we do: ``` if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { // AddressCache/address resolution didn't produce partition key range id. // In this case it is a bug. throw new IllegalStateException("Partition key range Id is absent in the context."); } ``` May be we should get rid of this exception clause then, instead of passing partitionId and keep passing empty string to be in parity with .Net ?
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
Discussed offline with @moderakh Final logic is, we will just get rid of `partitionKeyRangeId.isEmpty()` check.
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
class SessionTokenHelper { public static void setOriginalSessionToken(RxDocumentServiceRequest request, String originalSessionToken) { if (request == null) { throw new IllegalArgumentException("request is null"); } if (originalSessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, originalSessionToken); } } public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { throw new InternalServerErrorException(RMResources.PartitionKeyRangeIdAbsentInContext); } if (StringUtils.isNotEmpty(originalSessionToken)) { ISessionToken sessionToken = getLocalSessionToken(request, originalSessionToken, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } else { ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, partitionKeyRangeId); request.requestContext.sessionToken = sessionToken; } if (request.requestContext.sessionToken == null) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } else { request.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, concatPartitionKeyRangeIdWithSessionToken(partitionKeyRangeId, request.requestContext.sessionToken.convertToString())); } } private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, String partitionKeyRangeId) { if (partitionKeyRangeId == null) { throw new IllegalStateException("Partition key range Id is absent in the context."); } String[] localTokens = StringUtils.split(globalSessionToken, ","); Set<String> partitionKeyRangeSet = new HashSet<>(); partitionKeyRangeSet.add(partitionKeyRangeId); ISessionToken highestSessionToken = null; if (request.requestContext.resolvedPartitionKeyRange != null && request.requestContext.resolvedPartitionKeyRange.getParents() != null) { partitionKeyRangeSet.addAll(request.requestContext.resolvedPartitionKeyRange.getParents()); } for (String localToken : localTokens) { String[] items = StringUtils.split(localToken, ":"); if (items.length != 2) { throw new BadRequestException(String.format(RMResources.InvalidSessionToken, partitionKeyRangeId)); } ISessionToken parsedSessionToken = SessionTokenHelper.parse(items[1]); if (partitionKeyRangeSet.contains(items[0])) { if (highestSessionToken == null) { highestSessionToken = parsedSessionToken; } else { highestSessionToken = highestSessionToken.merge(parsedSessionToken); } } } return highestSessionToken; } static ISessionToken resolvePartitionLocalSessionToken(RxDocumentServiceRequest request, String partitionKeyRangeId, ConcurrentHashMap<String, ISessionToken> rangeIdToTokenMap) { if (rangeIdToTokenMap != null) { if (rangeIdToTokenMap.containsKey(partitionKeyRangeId)) { return rangeIdToTokenMap.get(partitionKeyRangeId); } else { Collection<String> parents = request.requestContext.resolvedPartitionKeyRange.getParents(); if (parents != null) { List<String> parentsList = new ArrayList<>(parents); for (int i = parentsList.size() - 1; i >= 0; i--) { String parentId = parentsList.get(i); if (rangeIdToTokenMap.containsKey(parentId)) { return rangeIdToTokenMap.get(parentId); } } } } } return null; } public static ISessionToken parse(String sessionToken) { ValueHolder<ISessionToken> partitionKeyRangeSessionToken = ValueHolder.initialize(null); if (SessionTokenHelper.tryParse(sessionToken, partitionKeyRangeSessionToken)) { return partitionKeyRangeSessionToken.v; } else { throw new RuntimeException(new BadRequestException(String.format(RMResources.InvalidSessionToken, sessionToken))); } } static boolean tryParse(String sessionToken, ValueHolder<ISessionToken> parsedSessionToken) { parsedSessionToken.v = null; if (!Strings.isNullOrEmpty(sessionToken)) { String[] sessionTokenSegments = StringUtils.split(sessionToken,":"); return VectorSessionToken.tryCreate(sessionTokenSegments[sessionTokenSegments.length - 1], parsedSessionToken); } else { return false; } } public static String concatPartitionKeyRangeIdWithSessionToken(String partitionKeyRangeRid, String sessionToken) { return partitionKeyRangeRid + ":" + sessionToken; } }
log and throw
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithMsalAccount(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(new AuthenticationRequiredException("Interactive authentication is needed to " + "acquire token. Call Authenticate to initiate the device code authentication.")); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); }
+ "acquire token. Call Authenticate to initiate the device code authentication."));
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithPublicClientCache(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(logger.logExceptionAsError(new AuthenticationRequiredException("Interactive " + "authentication is needed to acquire token. Call Authenticate to initiate the device " + "code authentication.", request))); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); }
class DeviceCodeCredential implements TokenCredential { private final Consumer<DeviceCodeInfo> challengeConsumer; private final IdentityClient identityClient; private final AtomicReference<MsalAuthenticationAccount> cachedToken; private final String authorityHost; private final boolean automaticAuthentication; /** * Creates a DeviceCodeCredential with the given identity client options. * * @param clientId the client ID of the application * @param tenantId the tenant ID of the application * @param challengeConsumer a method allowing the user to meet the device code challenge * @param identityClientOptions the options for configuring the identity client */ DeviceCodeCredential(String clientId, String tenantId, Consumer<DeviceCodeInfo> challengeConsumer, boolean automaticAuthentication, IdentityClientOptions identityClientOptions) { this.challengeConsumer = challengeConsumer; identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); this.cachedToken = new AtomicReference<>(); this.authorityHost = identityClientOptions.getAuthorityHost(); this.automaticAuthentication = automaticAuthentication; if (identityClientOptions.getAuthenticationRecord() != null) { cachedToken.set(new MsalAuthenticationAccount(identityClientOptions.getAuthenticationRecord())); } } @Override /** * Interactively authenticates a user via the default browser. * * @param request The details of the authentication request. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate(TokenRequestContext request) { return Mono.defer(() -> identityClient.authenticateWithDeviceCode(request, challengeConsumer)) .map(msalToken -> new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId())); } /** * Interactively authenticates a user via the default browser. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(new AuthenticationRequiredException("Authenticating in this environment requires" + " specifying a TokenRequestContext.")); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); } }
class DeviceCodeCredential implements TokenCredential { private final Consumer<DeviceCodeInfo> challengeConsumer; private final IdentityClient identityClient; private final AtomicReference<MsalAuthenticationAccount> cachedToken; private final String authorityHost; private final boolean automaticAuthentication; private final ClientLogger logger = new ClientLogger(DeviceCodeCredential.class); /** * Creates a DeviceCodeCredential with the given identity client options. * * @param clientId the client ID of the application * @param tenantId the tenant ID of the application * @param challengeConsumer a method allowing the user to meet the device code challenge * @param automaticAuthentication indicates whether automatic authentication should be attempted or not. * @param identityClientOptions the options for configuring the identity client */ DeviceCodeCredential(String clientId, String tenantId, Consumer<DeviceCodeInfo> challengeConsumer, boolean automaticAuthentication, IdentityClientOptions identityClientOptions) { this.challengeConsumer = challengeConsumer; identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); this.cachedToken = new AtomicReference<>(); this.authorityHost = identityClientOptions.getAuthorityHost(); this.automaticAuthentication = automaticAuthentication; if (identityClientOptions.getAuthenticationRecord() != null) { cachedToken.set(new MsalAuthenticationAccount(identityClientOptions.getAuthenticationRecord())); } } @Override /** * Authenticates a user via the device code flow. * * <p> The credential acquires a verification URL and code from the Azure Active Directory. The user must * browse to the URL, enter the code, and authenticate with Azure Active Directory. If the user authenticates * successfully, the credential receives an access token. </p> * * @param request The details of the authentication request. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate(TokenRequestContext request) { return Mono.defer(() -> identityClient.authenticateWithDeviceCode(request, challengeConsumer)) .map(msalToken -> new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId())); } /** * Authenticates a user via the device code flow. * * <p> The credential acquires a verification URL and code from the Azure Active Directory. The user must * browse to the URL, enter the code, and authenticate with Azure Active Directory. If the user authenticates * successfully, the credential receives an access token. </p> * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException("Authenticating in this " + "environment requires specifying a TokenRequestContext."))); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); } }
Shouldn't the exception carry `request` so the application can pass it on to `authenticate`?
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithMsalAccount(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(new AuthenticationRequiredException("Interactive authentication is needed to " + "acquire token. Call Authenticate to initiate the device code authentication.")); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); }
+ "acquire token. Call Authenticate to initiate the device code authentication."));
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithPublicClientCache(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(logger.logExceptionAsError(new AuthenticationRequiredException("Interactive " + "authentication is needed to acquire token. Call Authenticate to initiate the device " + "code authentication.", request))); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); }
class DeviceCodeCredential implements TokenCredential { private final Consumer<DeviceCodeInfo> challengeConsumer; private final IdentityClient identityClient; private final AtomicReference<MsalAuthenticationAccount> cachedToken; private final String authorityHost; private final boolean automaticAuthentication; /** * Creates a DeviceCodeCredential with the given identity client options. * * @param clientId the client ID of the application * @param tenantId the tenant ID of the application * @param challengeConsumer a method allowing the user to meet the device code challenge * @param identityClientOptions the options for configuring the identity client */ DeviceCodeCredential(String clientId, String tenantId, Consumer<DeviceCodeInfo> challengeConsumer, boolean automaticAuthentication, IdentityClientOptions identityClientOptions) { this.challengeConsumer = challengeConsumer; identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); this.cachedToken = new AtomicReference<>(); this.authorityHost = identityClientOptions.getAuthorityHost(); this.automaticAuthentication = automaticAuthentication; if (identityClientOptions.getAuthenticationRecord() != null) { cachedToken.set(new MsalAuthenticationAccount(identityClientOptions.getAuthenticationRecord())); } } @Override /** * Interactively authenticates a user via the default browser. * * @param request The details of the authentication request. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate(TokenRequestContext request) { return Mono.defer(() -> identityClient.authenticateWithDeviceCode(request, challengeConsumer)) .map(msalToken -> new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId())); } /** * Interactively authenticates a user via the default browser. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(new AuthenticationRequiredException("Authenticating in this environment requires" + " specifying a TokenRequestContext.")); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); } }
class DeviceCodeCredential implements TokenCredential { private final Consumer<DeviceCodeInfo> challengeConsumer; private final IdentityClient identityClient; private final AtomicReference<MsalAuthenticationAccount> cachedToken; private final String authorityHost; private final boolean automaticAuthentication; private final ClientLogger logger = new ClientLogger(DeviceCodeCredential.class); /** * Creates a DeviceCodeCredential with the given identity client options. * * @param clientId the client ID of the application * @param tenantId the tenant ID of the application * @param challengeConsumer a method allowing the user to meet the device code challenge * @param automaticAuthentication indicates whether automatic authentication should be attempted or not. * @param identityClientOptions the options for configuring the identity client */ DeviceCodeCredential(String clientId, String tenantId, Consumer<DeviceCodeInfo> challengeConsumer, boolean automaticAuthentication, IdentityClientOptions identityClientOptions) { this.challengeConsumer = challengeConsumer; identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); this.cachedToken = new AtomicReference<>(); this.authorityHost = identityClientOptions.getAuthorityHost(); this.automaticAuthentication = automaticAuthentication; if (identityClientOptions.getAuthenticationRecord() != null) { cachedToken.set(new MsalAuthenticationAccount(identityClientOptions.getAuthenticationRecord())); } } @Override /** * Authenticates a user via the device code flow. * * <p> The credential acquires a verification URL and code from the Azure Active Directory. The user must * browse to the URL, enter the code, and authenticate with Azure Active Directory. If the user authenticates * successfully, the credential receives an access token. </p> * * @param request The details of the authentication request. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate(TokenRequestContext request) { return Mono.defer(() -> identityClient.authenticateWithDeviceCode(request, challengeConsumer)) .map(msalToken -> new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId())); } /** * Authenticates a user via the device code flow. * * <p> The credential acquires a verification URL and code from the Azure Active Directory. The user must * browse to the URL, enter the code, and authenticate with Azure Active Directory. If the user authenticates * successfully, the credential receives an access token. </p> * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException("Authenticating in this " + "environment requires specifying a TokenRequestContext."))); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); } }
Yeah, added it.
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithMsalAccount(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(new AuthenticationRequiredException("Interactive authentication is needed to " + "acquire token. Call Authenticate to initiate the device code authentication.")); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); }
+ "acquire token. Call Authenticate to initiate the device code authentication."));
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithPublicClientCache(request, cachedToken.get()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> { if (!automaticAuthentication) { return Mono.error(logger.logExceptionAsError(new AuthenticationRequiredException("Interactive " + "authentication is needed to acquire token. Call Authenticate to initiate the device " + "code authentication.", request))); } return identityClient.authenticateWithDeviceCode(request, challengeConsumer); })) .map(msalToken -> { cachedToken.set( new MsalAuthenticationAccount( new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId()))); return msalToken; }); }
class DeviceCodeCredential implements TokenCredential { private final Consumer<DeviceCodeInfo> challengeConsumer; private final IdentityClient identityClient; private final AtomicReference<MsalAuthenticationAccount> cachedToken; private final String authorityHost; private final boolean automaticAuthentication; /** * Creates a DeviceCodeCredential with the given identity client options. * * @param clientId the client ID of the application * @param tenantId the tenant ID of the application * @param challengeConsumer a method allowing the user to meet the device code challenge * @param identityClientOptions the options for configuring the identity client */ DeviceCodeCredential(String clientId, String tenantId, Consumer<DeviceCodeInfo> challengeConsumer, boolean automaticAuthentication, IdentityClientOptions identityClientOptions) { this.challengeConsumer = challengeConsumer; identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); this.cachedToken = new AtomicReference<>(); this.authorityHost = identityClientOptions.getAuthorityHost(); this.automaticAuthentication = automaticAuthentication; if (identityClientOptions.getAuthenticationRecord() != null) { cachedToken.set(new MsalAuthenticationAccount(identityClientOptions.getAuthenticationRecord())); } } @Override /** * Interactively authenticates a user via the default browser. * * @param request The details of the authentication request. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate(TokenRequestContext request) { return Mono.defer(() -> identityClient.authenticateWithDeviceCode(request, challengeConsumer)) .map(msalToken -> new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId())); } /** * Interactively authenticates a user via the default browser. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(new AuthenticationRequiredException("Authenticating in this environment requires" + " specifying a TokenRequestContext.")); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); } }
class DeviceCodeCredential implements TokenCredential { private final Consumer<DeviceCodeInfo> challengeConsumer; private final IdentityClient identityClient; private final AtomicReference<MsalAuthenticationAccount> cachedToken; private final String authorityHost; private final boolean automaticAuthentication; private final ClientLogger logger = new ClientLogger(DeviceCodeCredential.class); /** * Creates a DeviceCodeCredential with the given identity client options. * * @param clientId the client ID of the application * @param tenantId the tenant ID of the application * @param challengeConsumer a method allowing the user to meet the device code challenge * @param automaticAuthentication indicates whether automatic authentication should be attempted or not. * @param identityClientOptions the options for configuring the identity client */ DeviceCodeCredential(String clientId, String tenantId, Consumer<DeviceCodeInfo> challengeConsumer, boolean automaticAuthentication, IdentityClientOptions identityClientOptions) { this.challengeConsumer = challengeConsumer; identityClient = new IdentityClientBuilder() .tenantId(tenantId) .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); this.cachedToken = new AtomicReference<>(); this.authorityHost = identityClientOptions.getAuthorityHost(); this.automaticAuthentication = automaticAuthentication; if (identityClientOptions.getAuthenticationRecord() != null) { cachedToken.set(new MsalAuthenticationAccount(identityClientOptions.getAuthenticationRecord())); } } @Override /** * Authenticates a user via the device code flow. * * <p> The credential acquires a verification URL and code from the Azure Active Directory. The user must * browse to the URL, enter the code, and authenticate with Azure Active Directory. If the user authenticates * successfully, the credential receives an access token. </p> * * @param request The details of the authentication request. * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate(TokenRequestContext request) { return Mono.defer(() -> identityClient.authenticateWithDeviceCode(request, challengeConsumer)) .map(msalToken -> new AuthenticationRecord(msalToken.getAuthenticationResult(), identityClient.getTenantId())); } /** * Authenticates a user via the device code flow. * * <p> The credential acquires a verification URL and code from the Azure Active Directory. The user must * browse to the URL, enter the code, and authenticate with Azure Active Directory. If the user authenticates * successfully, the credential receives an access token. </p> * * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account * on future execution if persistent caching was enabled via * {@link DeviceCodeCredentialBuilder */ public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException("Authenticating in this " + "environment requires specifying a TokenRequestContext."))); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); } }
Do you mean to keep this?
public void testValidAuthenticate() throws Exception { Random random = new Random(); String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); int port = random.nextInt(10000) + 10000; IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateWithBrowserInteraction(eq(request1), eq(port))) .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder().port(port).clientId(clientId).build(); StepVerifier.create(credential.authenticate(request1)) .expectNextMatches(authenticationRecord -> authenticationRecord.getAuthority() .equals("http: && authenticationRecord.getUsername().equals("testuser") && authenticationRecord.getHomeAccountId() != null) .verifyComplete(); }
public void testValidAuthenticate() throws Exception { Random random = new Random(); String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); int port = random.nextInt(10000) + 10000; IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateWithBrowserInteraction(eq(request1), eq(port))) .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder().port(port).clientId(clientId).build(); StepVerifier.create(credential.authenticate(request1)) .expectNextMatches(authenticationRecord -> authenticationRecord.getAuthority() .equals("http: && authenticationRecord.getUsername().equals("testuser") && authenticationRecord.getHomeAccountId() != null) .verifyComplete(); }
class InteractiveBrowserCredentialTest { private final String tenantId = "contoso.com"; private final String clientId = UUID.randomUUID().toString(); @Test public void testValidInteractive() throws Exception { Random random = new Random(); String token1 = "token1"; String token2 = "token2"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: TokenRequestContext request2 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); int port = random.nextInt(10000) + 10000; IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateWithBrowserInteraction(eq(request1), eq(port))).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); when(identityClient.authenticateWithMsalAccount(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalToken(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder().port(port).clientId(clientId).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(accessToken -> token1.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); StepVerifier.create(credential.getToken(request2)) .expectNextMatches(accessToken -> token2.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); } @Test }
class InteractiveBrowserCredentialTest { private final String tenantId = "contoso.com"; private final String clientId = UUID.randomUUID().toString(); @Test public void testValidInteractive() throws Exception { Random random = new Random(); String token1 = "token1"; String token2 = "token2"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: TokenRequestContext request2 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); int port = random.nextInt(10000) + 10000; IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateWithBrowserInteraction(eq(request1), eq(port))).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalToken(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder().port(port).clientId(clientId).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(accessToken -> token1.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); StepVerifier.create(credential.getToken(request2)) .expectNextMatches(accessToken -> token2.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); } @Test }
Instead of converting instant to OffsetDateTime, its better to add this helper method in Utils.java which directly takes Instant and formats it. ``` public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant); } ```
private RxDocumentServiceRequest createDocumentServiceRequest(String continuationToken, int pageSize) { Map<String, String> headers = new HashMap<>(); RxDocumentServiceRequest req = RxDocumentServiceRequest.create( OperationType.ReadFeed, resourceType, documentsLink, headers, options); if (options.getMaxItemCount() != null) { headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, String.valueOf(options.getMaxItemCount())); } if(continuationToken != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, continuationToken); } headers.put(HttpConstants.HttpHeaders.A_IM, HttpConstants.A_IMHeaderValues.INCREMENTAL_FEED); if (options.getPartitionKey() != null) { PartitionKeyInternal partitionKey = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); headers.put(HttpConstants.HttpHeaders.PARTITION_KEY, partitionKey.toJson()); req.setPartitionKeyInternal(partitionKey); } if(options.getStartDateTime() != null){ String dateTimeInHttpFormat = Utils.zonedDateTimeAsUTCRFC1123(options.getStartDateTime().atOffset(ZoneOffset.UTC)); headers.put(HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, dateTimeInHttpFormat); } if (options.getPartitionKeyRangeId() != null) { req.routeTo(new PartitionKeyRangeIdentity(this.options.getPartitionKeyRangeId())); } return req; }
String dateTimeInHttpFormat = Utils.zonedDateTimeAsUTCRFC1123(options.getStartDateTime().atOffset(ZoneOffset.UTC));
private RxDocumentServiceRequest createDocumentServiceRequest(String continuationToken, int pageSize) { Map<String, String> headers = new HashMap<>(); RxDocumentServiceRequest req = RxDocumentServiceRequest.create( OperationType.ReadFeed, resourceType, documentsLink, headers, options); if (options.getMaxItemCount() != null) { headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, String.valueOf(options.getMaxItemCount())); } if(continuationToken != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, continuationToken); } headers.put(HttpConstants.HttpHeaders.A_IM, HttpConstants.A_IMHeaderValues.INCREMENTAL_FEED); if (options.getPartitionKey() != null) { PartitionKeyInternal partitionKey = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); headers.put(HttpConstants.HttpHeaders.PARTITION_KEY, partitionKey.toJson()); req.setPartitionKeyInternal(partitionKey); } if(options.getStartDateTime() != null){ String dateTimeInHttpFormat = Utils.zonedDateTimeAsUTCRFC1123(options.getStartDateTime().atOffset(ZoneOffset.UTC)); headers.put(HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, dateTimeInHttpFormat); } if (options.getPartitionKeyRangeId() != null) { req.routeTo(new PartitionKeyRangeIdentity(this.options.getPartitionKeyRangeId())); } return req; }
class ChangeFeedQueryImpl<T extends Resource> { private static final String IfNonMatchAllHeaderValue = "*"; private final RxDocumentClientImpl client; private final ResourceType resourceType; private final Class<T> klass; private final String documentsLink; private final ChangeFeedOptions options; public ChangeFeedQueryImpl(RxDocumentClientImpl client, ResourceType resourceType, Class<T> klass, String collectionLink, ChangeFeedOptions changeFeedOptions) { this.client = client; this.resourceType = resourceType; this.klass = klass; this.documentsLink = Utils.joinPath(collectionLink, Paths.DOCUMENTS_PATH_SEGMENT); changeFeedOptions = changeFeedOptions != null ? changeFeedOptions: new ChangeFeedOptions(); if (resourceType.isPartitioned() && changeFeedOptions.getPartitionKeyRangeId() == null && changeFeedOptions.getPartitionKey() == null) { throw new IllegalArgumentException(RMResources.PartitionKeyRangeIdOrPartitionKeyMustBeSpecified); } if (changeFeedOptions.getPartitionKey() != null && !Strings.isNullOrEmpty(changeFeedOptions.getPartitionKeyRangeId())) { throw new IllegalArgumentException(String.format( RMResources.PartitionKeyAndParitionKeyRangeIdBothSpecified , "feedOptions")); } String initialNextIfNoneMatch = null; boolean canUseStartFromBeginning = true; if (changeFeedOptions.getRequestContinuation() != null) { initialNextIfNoneMatch = changeFeedOptions.getRequestContinuation(); canUseStartFromBeginning = false; } if(changeFeedOptions.getStartDateTime() != null){ canUseStartFromBeginning = false; } if (canUseStartFromBeginning && !changeFeedOptions.isStartFromBeginning()) { initialNextIfNoneMatch = IfNonMatchAllHeaderValue; } this.options = getChangeFeedOptions(changeFeedOptions, initialNextIfNoneMatch); } private ChangeFeedOptions getChangeFeedOptions(ChangeFeedOptions options, String continuationToken) { ChangeFeedOptions newOps = new ChangeFeedOptions(options); newOps.setRequestContinuation(continuationToken); return newOps; } public Flux<FeedResponse<T>> executeAsync() { BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = this::createDocumentServiceRequest; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = this::executeRequestAsync; return Paginator.getPaginatedChangeFeedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, options.getMaxItemCount() != null ? options.getMaxItemCount(): -1); } private Mono<FeedResponse<T>> executeRequestAsync(RxDocumentServiceRequest request) { return client.readFeed(request) .map( rsp -> BridgeInternal.toChangeFeedResponsePage(rsp, klass)); } }
class ChangeFeedQueryImpl<T extends Resource> { private static final String IfNonMatchAllHeaderValue = "*"; private final RxDocumentClientImpl client; private final ResourceType resourceType; private final Class<T> klass; private final String documentsLink; private final ChangeFeedOptions options; public ChangeFeedQueryImpl(RxDocumentClientImpl client, ResourceType resourceType, Class<T> klass, String collectionLink, ChangeFeedOptions changeFeedOptions) { this.client = client; this.resourceType = resourceType; this.klass = klass; this.documentsLink = Utils.joinPath(collectionLink, Paths.DOCUMENTS_PATH_SEGMENT); changeFeedOptions = changeFeedOptions != null ? changeFeedOptions: new ChangeFeedOptions(); if (resourceType.isPartitioned() && changeFeedOptions.getPartitionKeyRangeId() == null && changeFeedOptions.getPartitionKey() == null) { throw new IllegalArgumentException(RMResources.PartitionKeyRangeIdOrPartitionKeyMustBeSpecified); } if (changeFeedOptions.getPartitionKey() != null && !Strings.isNullOrEmpty(changeFeedOptions.getPartitionKeyRangeId())) { throw new IllegalArgumentException(String.format( RMResources.PartitionKeyAndParitionKeyRangeIdBothSpecified , "feedOptions")); } String initialNextIfNoneMatch = null; boolean canUseStartFromBeginning = true; if (changeFeedOptions.getRequestContinuation() != null) { initialNextIfNoneMatch = changeFeedOptions.getRequestContinuation(); canUseStartFromBeginning = false; } if(changeFeedOptions.getStartDateTime() != null){ canUseStartFromBeginning = false; } if (canUseStartFromBeginning && !changeFeedOptions.isStartFromBeginning()) { initialNextIfNoneMatch = IfNonMatchAllHeaderValue; } this.options = getChangeFeedOptions(changeFeedOptions, initialNextIfNoneMatch); } private ChangeFeedOptions getChangeFeedOptions(ChangeFeedOptions options, String continuationToken) { ChangeFeedOptions newOps = new ChangeFeedOptions(options); newOps.setRequestContinuation(continuationToken); return newOps; } public Flux<FeedResponse<T>> executeAsync() { BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = this::createDocumentServiceRequest; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = this::executeRequestAsync; return Paginator.getPaginatedChangeFeedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, options.getMaxItemCount() != null ? options.getMaxItemCount(): -1); } private Mono<FeedResponse<T>> executeRequestAsync(RxDocumentServiceRequest request) { return client.readFeed(request) .map( rsp -> BridgeInternal.toChangeFeedResponsePage(rsp, klass)); } }
why are we doing translation from ZoneDateTime to Instant? can't we rely on Instant everywhere? @simplynaveen20 @milismsft
public static ServiceItemLease fromDocument(CosmosItemProperties document) { ServiceItemLease lease = new ServiceItemLease() .withId(document.getId()) .withETag(document.getETag()) .withTs(ModelBridgeInternal.getStringFromJsonSerializable(document, Constants.Properties.LAST_MODIFIED)) .withOwner(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_OWNER)) .withLeaseToken(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_LEASE_TOKEN)) .withContinuationToken(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_CONTINUATION_TOKEN)); String leaseTimestamp = ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_TIMESTAMP); if (leaseTimestamp != null) { return lease.withTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant()); } else { return lease; } }
return lease.withTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant());
public static ServiceItemLease fromDocument(CosmosItemProperties document) { ServiceItemLease lease = new ServiceItemLease() .withId(document.getId()) .withETag(document.getETag()) .withTs(ModelBridgeInternal.getStringFromJsonSerializable(document, Constants.Properties.LAST_MODIFIED)) .withOwner(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_OWNER)) .withLeaseToken(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_LEASE_TOKEN)) .withContinuationToken(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_CONTINUATION_TOKEN)); String leaseTimestamp = ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_TIMESTAMP); if (leaseTimestamp != null) { return lease.withTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant()); } else { return lease; } }
class ServiceItemLease implements Lease { private static final ZonedDateTime UNIX_START_TIME = ZonedDateTime.parse("1970-01-01T00:00:00.0Z[UTC]"); private static final String PROPERTY_NAME_LEASE_TOKEN = "LeaseToken"; private static final String PROPERTY_NAME_CONTINUATION_TOKEN = "ContinuationToken"; private static final String PROPERTY_NAME_TIMESTAMP = "timestamp"; private static final String PROPERTY_NAME_OWNER = "Owner"; private String id; private String _etag; private String LeaseToken; private String Owner; private String ContinuationToken; private Map<String, String> properties; private String timestamp; private String _ts; public ServiceItemLease() { ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("UTC")); this.timestamp = currentTime.toString(); this._ts = String.valueOf(currentTime.getSecond()); this.properties = new HashMap<>(); } public ServiceItemLease(ServiceItemLease other) { this.id = other.id; this._etag = other._etag; this.LeaseToken = other.LeaseToken; this.Owner = other.Owner; this.ContinuationToken = other.ContinuationToken; this.properties = other.properties; this.timestamp = other.timestamp; this._ts = other._ts; } @Override public String getId() { return this.id; } public ServiceItemLease withId(String id) { this.id = id; return this; } public String getETag() { return this._etag; } public ServiceItemLease withETag(String etag) { this._etag = etag; return this; } public String getLeaseToken() { return this.LeaseToken; } public ServiceItemLease withLeaseToken(String leaseToken) { this.LeaseToken = leaseToken; return this; } @Override public String getOwner() { return this.Owner; } public ServiceItemLease withOwner(String owner) { this.Owner = owner; return this; } @Override public String getContinuationToken() { return this.ContinuationToken; } @Override public void setContinuationToken(String continuationToken) { this.withContinuationToken(continuationToken); } public ServiceItemLease withContinuationToken(String continuationToken) { this.ContinuationToken = continuationToken; return this; } @Override public Map<String, String> getProperties() { return this.properties; } @Override public void setOwner(String owner) { this.withOwner(owner); } @Override public void setTimestamp(Instant timestamp) { this.withTimestamp(timestamp); } public void setTimestamp(Date date) { this.withTimestamp(date.toInstant()); } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } @Override public void setId(String id) { this.withId(id); } @Override public void setConcurrencyToken(String concurrencyToken) { this.withETag(concurrencyToken); } public ServiceItemLease withConcurrencyToken(String concurrencyToken) { return this.withETag(concurrencyToken); } @Override public void setProperties(Map<String, String> properties) { this.withProperties(properties); } public ServiceItemLease withProperties(Map<String, String> properties) { this.properties = properties; return this; } public String getTs() { return this._ts; } public ServiceItemLease withTs(String ts) { this._ts = ts; return this; } @Override public String getTimestamp() { if (this.timestamp == null) { return UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs())).toString(); } return this.timestamp; } public ServiceItemLease withTimestamp(Instant timestamp) { this.timestamp = timestamp.toString(); return this; } public String getExplicitTimestamp() { return this.timestamp; } @Override public String getConcurrencyToken() { return this.getETag(); } public void setServiceItemLease(Lease lease) { this.setId(lease.getId()); this.setConcurrencyToken(lease.getConcurrencyToken()); this.setOwner(lease.getOwner()); this.withLeaseToken(lease.getLeaseToken()); this.setContinuationToken(getContinuationToken()); String leaseTimestamp = lease.getTimestamp(); if (leaseTimestamp != null) { this.setTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant()); } else { this.setTimestamp(lease.getTimestamp()); } } @Override public String toString() { return String.format( "%s Owner='%s' Continuation=%s Timestamp(local)=%s Timestamp(server)=%s", this.getId(), this.getOwner(), this.getContinuationToken(), this.getTimestamp(), UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs()))); } @SuppressWarnings("serial") static final class ServiceItemLeaseJsonSerializer extends StdSerializer<ServiceItemLease> { private static final long serialVersionUID = 1L; protected ServiceItemLeaseJsonSerializer() { this(null); } protected ServiceItemLeaseJsonSerializer(Class<ServiceItemLease> t) { super(t); } @Override public void serialize(ServiceItemLease lease, JsonGenerator writer, SerializerProvider serializerProvider) { try { writer.writeStartObject(); writer.writeStringField(Constants.Properties.ID, lease.getId()); writer.writeStringField(Constants.Properties.E_TAG, lease.getETag()); writer.writeStringField(PROPERTY_NAME_LEASE_TOKEN, lease.getLeaseToken()); writer.writeStringField(PROPERTY_NAME_CONTINUATION_TOKEN, lease.getContinuationToken()); writer.writeStringField(PROPERTY_NAME_TIMESTAMP, lease.getTimestamp()); writer.writeStringField(PROPERTY_NAME_OWNER, lease.getOwner()); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } } }
class ServiceItemLease implements Lease { private static final ZonedDateTime UNIX_START_TIME = ZonedDateTime.parse("1970-01-01T00:00:00.0Z[UTC]"); private static final String PROPERTY_NAME_LEASE_TOKEN = "LeaseToken"; private static final String PROPERTY_NAME_CONTINUATION_TOKEN = "ContinuationToken"; private static final String PROPERTY_NAME_TIMESTAMP = "timestamp"; private static final String PROPERTY_NAME_OWNER = "Owner"; private String id; private String _etag; private String LeaseToken; private String Owner; private String ContinuationToken; private Map<String, String> properties; private String timestamp; private String _ts; public ServiceItemLease() { ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("UTC")); this.timestamp = currentTime.toString(); this._ts = String.valueOf(currentTime.getSecond()); this.properties = new HashMap<>(); } public ServiceItemLease(ServiceItemLease other) { this.id = other.id; this._etag = other._etag; this.LeaseToken = other.LeaseToken; this.Owner = other.Owner; this.ContinuationToken = other.ContinuationToken; this.properties = other.properties; this.timestamp = other.timestamp; this._ts = other._ts; } @Override public String getId() { return this.id; } public ServiceItemLease withId(String id) { this.id = id; return this; } public String getETag() { return this._etag; } public ServiceItemLease withETag(String etag) { this._etag = etag; return this; } public String getLeaseToken() { return this.LeaseToken; } public ServiceItemLease withLeaseToken(String leaseToken) { this.LeaseToken = leaseToken; return this; } @Override public String getOwner() { return this.Owner; } public ServiceItemLease withOwner(String owner) { this.Owner = owner; return this; } @Override public String getContinuationToken() { return this.ContinuationToken; } @Override public void setContinuationToken(String continuationToken) { this.withContinuationToken(continuationToken); } public ServiceItemLease withContinuationToken(String continuationToken) { this.ContinuationToken = continuationToken; return this; } @Override public Map<String, String> getProperties() { return this.properties; } @Override public void setOwner(String owner) { this.withOwner(owner); } @Override public void setTimestamp(Instant timestamp) { this.withTimestamp(timestamp); } public void setTimestamp(Date date) { this.withTimestamp(date.toInstant()); } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } @Override public void setId(String id) { this.withId(id); } @Override public void setConcurrencyToken(String concurrencyToken) { this.withETag(concurrencyToken); } public ServiceItemLease withConcurrencyToken(String concurrencyToken) { return this.withETag(concurrencyToken); } @Override public void setProperties(Map<String, String> properties) { this.withProperties(properties); } public ServiceItemLease withProperties(Map<String, String> properties) { this.properties = properties; return this; } public String getTs() { return this._ts; } public ServiceItemLease withTs(String ts) { this._ts = ts; return this; } @Override public String getTimestamp() { if (this.timestamp == null) { return UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs())).toString(); } return this.timestamp; } public ServiceItemLease withTimestamp(Instant timestamp) { this.timestamp = timestamp.toString(); return this; } public String getExplicitTimestamp() { return this.timestamp; } @Override public String getConcurrencyToken() { return this.getETag(); } public void setServiceItemLease(Lease lease) { this.setId(lease.getId()); this.setConcurrencyToken(lease.getConcurrencyToken()); this.setOwner(lease.getOwner()); this.withLeaseToken(lease.getLeaseToken()); this.setContinuationToken(getContinuationToken()); String leaseTimestamp = lease.getTimestamp(); if (leaseTimestamp != null) { this.setTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant()); } else { this.setTimestamp(lease.getTimestamp()); } } @Override public String toString() { return String.format( "%s Owner='%s' Continuation=%s Timestamp(local)=%s Timestamp(server)=%s", this.getId(), this.getOwner(), this.getContinuationToken(), this.getTimestamp(), UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs()))); } @SuppressWarnings("serial") static final class ServiceItemLeaseJsonSerializer extends StdSerializer<ServiceItemLease> { private static final long serialVersionUID = 1L; protected ServiceItemLeaseJsonSerializer() { this(null); } protected ServiceItemLeaseJsonSerializer(Class<ServiceItemLease> t) { super(t); } @Override public void serialize(ServiceItemLease lease, JsonGenerator writer, SerializerProvider serializerProvider) { try { writer.writeStartObject(); writer.writeStringField(Constants.Properties.ID, lease.getId()); writer.writeStringField(Constants.Properties.E_TAG, lease.getETag()); writer.writeStringField(PROPERTY_NAME_LEASE_TOKEN, lease.getLeaseToken()); writer.writeStringField(PROPERTY_NAME_CONTINUATION_TOKEN, lease.getContinuationToken()); writer.writeStringField(PROPERTY_NAME_TIMESTAMP, lease.getTimestamp()); writer.writeStringField(PROPERTY_NAME_OWNER, lease.getOwner()); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } } }
Discussed with Milis, we are serializing and deserializing the same way it was happening before , also text coming from service is in DateTime format which cant be parse with Instant, it will throw exception
public static ServiceItemLease fromDocument(CosmosItemProperties document) { ServiceItemLease lease = new ServiceItemLease() .withId(document.getId()) .withETag(document.getETag()) .withTs(ModelBridgeInternal.getStringFromJsonSerializable(document, Constants.Properties.LAST_MODIFIED)) .withOwner(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_OWNER)) .withLeaseToken(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_LEASE_TOKEN)) .withContinuationToken(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_CONTINUATION_TOKEN)); String leaseTimestamp = ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_TIMESTAMP); if (leaseTimestamp != null) { return lease.withTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant()); } else { return lease; } }
return lease.withTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant());
public static ServiceItemLease fromDocument(CosmosItemProperties document) { ServiceItemLease lease = new ServiceItemLease() .withId(document.getId()) .withETag(document.getETag()) .withTs(ModelBridgeInternal.getStringFromJsonSerializable(document, Constants.Properties.LAST_MODIFIED)) .withOwner(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_OWNER)) .withLeaseToken(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_LEASE_TOKEN)) .withContinuationToken(ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_CONTINUATION_TOKEN)); String leaseTimestamp = ModelBridgeInternal.getStringFromJsonSerializable(document,PROPERTY_NAME_TIMESTAMP); if (leaseTimestamp != null) { return lease.withTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant()); } else { return lease; } }
class ServiceItemLease implements Lease { private static final ZonedDateTime UNIX_START_TIME = ZonedDateTime.parse("1970-01-01T00:00:00.0Z[UTC]"); private static final String PROPERTY_NAME_LEASE_TOKEN = "LeaseToken"; private static final String PROPERTY_NAME_CONTINUATION_TOKEN = "ContinuationToken"; private static final String PROPERTY_NAME_TIMESTAMP = "timestamp"; private static final String PROPERTY_NAME_OWNER = "Owner"; private String id; private String _etag; private String LeaseToken; private String Owner; private String ContinuationToken; private Map<String, String> properties; private String timestamp; private String _ts; public ServiceItemLease() { ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("UTC")); this.timestamp = currentTime.toString(); this._ts = String.valueOf(currentTime.getSecond()); this.properties = new HashMap<>(); } public ServiceItemLease(ServiceItemLease other) { this.id = other.id; this._etag = other._etag; this.LeaseToken = other.LeaseToken; this.Owner = other.Owner; this.ContinuationToken = other.ContinuationToken; this.properties = other.properties; this.timestamp = other.timestamp; this._ts = other._ts; } @Override public String getId() { return this.id; } public ServiceItemLease withId(String id) { this.id = id; return this; } public String getETag() { return this._etag; } public ServiceItemLease withETag(String etag) { this._etag = etag; return this; } public String getLeaseToken() { return this.LeaseToken; } public ServiceItemLease withLeaseToken(String leaseToken) { this.LeaseToken = leaseToken; return this; } @Override public String getOwner() { return this.Owner; } public ServiceItemLease withOwner(String owner) { this.Owner = owner; return this; } @Override public String getContinuationToken() { return this.ContinuationToken; } @Override public void setContinuationToken(String continuationToken) { this.withContinuationToken(continuationToken); } public ServiceItemLease withContinuationToken(String continuationToken) { this.ContinuationToken = continuationToken; return this; } @Override public Map<String, String> getProperties() { return this.properties; } @Override public void setOwner(String owner) { this.withOwner(owner); } @Override public void setTimestamp(Instant timestamp) { this.withTimestamp(timestamp); } public void setTimestamp(Date date) { this.withTimestamp(date.toInstant()); } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } @Override public void setId(String id) { this.withId(id); } @Override public void setConcurrencyToken(String concurrencyToken) { this.withETag(concurrencyToken); } public ServiceItemLease withConcurrencyToken(String concurrencyToken) { return this.withETag(concurrencyToken); } @Override public void setProperties(Map<String, String> properties) { this.withProperties(properties); } public ServiceItemLease withProperties(Map<String, String> properties) { this.properties = properties; return this; } public String getTs() { return this._ts; } public ServiceItemLease withTs(String ts) { this._ts = ts; return this; } @Override public String getTimestamp() { if (this.timestamp == null) { return UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs())).toString(); } return this.timestamp; } public ServiceItemLease withTimestamp(Instant timestamp) { this.timestamp = timestamp.toString(); return this; } public String getExplicitTimestamp() { return this.timestamp; } @Override public String getConcurrencyToken() { return this.getETag(); } public void setServiceItemLease(Lease lease) { this.setId(lease.getId()); this.setConcurrencyToken(lease.getConcurrencyToken()); this.setOwner(lease.getOwner()); this.withLeaseToken(lease.getLeaseToken()); this.setContinuationToken(getContinuationToken()); String leaseTimestamp = lease.getTimestamp(); if (leaseTimestamp != null) { this.setTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant()); } else { this.setTimestamp(lease.getTimestamp()); } } @Override public String toString() { return String.format( "%s Owner='%s' Continuation=%s Timestamp(local)=%s Timestamp(server)=%s", this.getId(), this.getOwner(), this.getContinuationToken(), this.getTimestamp(), UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs()))); } @SuppressWarnings("serial") static final class ServiceItemLeaseJsonSerializer extends StdSerializer<ServiceItemLease> { private static final long serialVersionUID = 1L; protected ServiceItemLeaseJsonSerializer() { this(null); } protected ServiceItemLeaseJsonSerializer(Class<ServiceItemLease> t) { super(t); } @Override public void serialize(ServiceItemLease lease, JsonGenerator writer, SerializerProvider serializerProvider) { try { writer.writeStartObject(); writer.writeStringField(Constants.Properties.ID, lease.getId()); writer.writeStringField(Constants.Properties.E_TAG, lease.getETag()); writer.writeStringField(PROPERTY_NAME_LEASE_TOKEN, lease.getLeaseToken()); writer.writeStringField(PROPERTY_NAME_CONTINUATION_TOKEN, lease.getContinuationToken()); writer.writeStringField(PROPERTY_NAME_TIMESTAMP, lease.getTimestamp()); writer.writeStringField(PROPERTY_NAME_OWNER, lease.getOwner()); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } } }
class ServiceItemLease implements Lease { private static final ZonedDateTime UNIX_START_TIME = ZonedDateTime.parse("1970-01-01T00:00:00.0Z[UTC]"); private static final String PROPERTY_NAME_LEASE_TOKEN = "LeaseToken"; private static final String PROPERTY_NAME_CONTINUATION_TOKEN = "ContinuationToken"; private static final String PROPERTY_NAME_TIMESTAMP = "timestamp"; private static final String PROPERTY_NAME_OWNER = "Owner"; private String id; private String _etag; private String LeaseToken; private String Owner; private String ContinuationToken; private Map<String, String> properties; private String timestamp; private String _ts; public ServiceItemLease() { ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("UTC")); this.timestamp = currentTime.toString(); this._ts = String.valueOf(currentTime.getSecond()); this.properties = new HashMap<>(); } public ServiceItemLease(ServiceItemLease other) { this.id = other.id; this._etag = other._etag; this.LeaseToken = other.LeaseToken; this.Owner = other.Owner; this.ContinuationToken = other.ContinuationToken; this.properties = other.properties; this.timestamp = other.timestamp; this._ts = other._ts; } @Override public String getId() { return this.id; } public ServiceItemLease withId(String id) { this.id = id; return this; } public String getETag() { return this._etag; } public ServiceItemLease withETag(String etag) { this._etag = etag; return this; } public String getLeaseToken() { return this.LeaseToken; } public ServiceItemLease withLeaseToken(String leaseToken) { this.LeaseToken = leaseToken; return this; } @Override public String getOwner() { return this.Owner; } public ServiceItemLease withOwner(String owner) { this.Owner = owner; return this; } @Override public String getContinuationToken() { return this.ContinuationToken; } @Override public void setContinuationToken(String continuationToken) { this.withContinuationToken(continuationToken); } public ServiceItemLease withContinuationToken(String continuationToken) { this.ContinuationToken = continuationToken; return this; } @Override public Map<String, String> getProperties() { return this.properties; } @Override public void setOwner(String owner) { this.withOwner(owner); } @Override public void setTimestamp(Instant timestamp) { this.withTimestamp(timestamp); } public void setTimestamp(Date date) { this.withTimestamp(date.toInstant()); } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } @Override public void setId(String id) { this.withId(id); } @Override public void setConcurrencyToken(String concurrencyToken) { this.withETag(concurrencyToken); } public ServiceItemLease withConcurrencyToken(String concurrencyToken) { return this.withETag(concurrencyToken); } @Override public void setProperties(Map<String, String> properties) { this.withProperties(properties); } public ServiceItemLease withProperties(Map<String, String> properties) { this.properties = properties; return this; } public String getTs() { return this._ts; } public ServiceItemLease withTs(String ts) { this._ts = ts; return this; } @Override public String getTimestamp() { if (this.timestamp == null) { return UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs())).toString(); } return this.timestamp; } public ServiceItemLease withTimestamp(Instant timestamp) { this.timestamp = timestamp.toString(); return this; } public String getExplicitTimestamp() { return this.timestamp; } @Override public String getConcurrencyToken() { return this.getETag(); } public void setServiceItemLease(Lease lease) { this.setId(lease.getId()); this.setConcurrencyToken(lease.getConcurrencyToken()); this.setOwner(lease.getOwner()); this.withLeaseToken(lease.getLeaseToken()); this.setContinuationToken(getContinuationToken()); String leaseTimestamp = lease.getTimestamp(); if (leaseTimestamp != null) { this.setTimestamp(ZonedDateTime.parse(leaseTimestamp).toInstant()); } else { this.setTimestamp(lease.getTimestamp()); } } @Override public String toString() { return String.format( "%s Owner='%s' Continuation=%s Timestamp(local)=%s Timestamp(server)=%s", this.getId(), this.getOwner(), this.getContinuationToken(), this.getTimestamp(), UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs()))); } @SuppressWarnings("serial") static final class ServiceItemLeaseJsonSerializer extends StdSerializer<ServiceItemLease> { private static final long serialVersionUID = 1L; protected ServiceItemLeaseJsonSerializer() { this(null); } protected ServiceItemLeaseJsonSerializer(Class<ServiceItemLease> t) { super(t); } @Override public void serialize(ServiceItemLease lease, JsonGenerator writer, SerializerProvider serializerProvider) { try { writer.writeStartObject(); writer.writeStringField(Constants.Properties.ID, lease.getId()); writer.writeStringField(Constants.Properties.E_TAG, lease.getETag()); writer.writeStringField(PROPERTY_NAME_LEASE_TOKEN, lease.getLeaseToken()); writer.writeStringField(PROPERTY_NAME_CONTINUATION_TOKEN, lease.getContinuationToken()); writer.writeStringField(PROPERTY_NAME_TIMESTAMP, lease.getTimestamp()); writer.writeStringField(PROPERTY_NAME_OWNER, lease.getOwner()); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } } } }
DateTime format cannot parse with Instant , we need zone time info , it will give runtime exception. Also we it cant be compatible with existing lease if we change the format. https://stackoverflow.com/questions/25229124/format-instant-to-string
private RxDocumentServiceRequest createDocumentServiceRequest(String continuationToken, int pageSize) { Map<String, String> headers = new HashMap<>(); RxDocumentServiceRequest req = RxDocumentServiceRequest.create( OperationType.ReadFeed, resourceType, documentsLink, headers, options); if (options.getMaxItemCount() != null) { headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, String.valueOf(options.getMaxItemCount())); } if(continuationToken != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, continuationToken); } headers.put(HttpConstants.HttpHeaders.A_IM, HttpConstants.A_IMHeaderValues.INCREMENTAL_FEED); if (options.getPartitionKey() != null) { PartitionKeyInternal partitionKey = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); headers.put(HttpConstants.HttpHeaders.PARTITION_KEY, partitionKey.toJson()); req.setPartitionKeyInternal(partitionKey); } if(options.getStartDateTime() != null){ String dateTimeInHttpFormat = Utils.zonedDateTimeAsUTCRFC1123(options.getStartDateTime().atOffset(ZoneOffset.UTC)); headers.put(HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, dateTimeInHttpFormat); } if (options.getPartitionKeyRangeId() != null) { req.routeTo(new PartitionKeyRangeIdentity(this.options.getPartitionKeyRangeId())); } return req; }
String dateTimeInHttpFormat = Utils.zonedDateTimeAsUTCRFC1123(options.getStartDateTime().atOffset(ZoneOffset.UTC));
private RxDocumentServiceRequest createDocumentServiceRequest(String continuationToken, int pageSize) { Map<String, String> headers = new HashMap<>(); RxDocumentServiceRequest req = RxDocumentServiceRequest.create( OperationType.ReadFeed, resourceType, documentsLink, headers, options); if (options.getMaxItemCount() != null) { headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, String.valueOf(options.getMaxItemCount())); } if(continuationToken != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, continuationToken); } headers.put(HttpConstants.HttpHeaders.A_IM, HttpConstants.A_IMHeaderValues.INCREMENTAL_FEED); if (options.getPartitionKey() != null) { PartitionKeyInternal partitionKey = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); headers.put(HttpConstants.HttpHeaders.PARTITION_KEY, partitionKey.toJson()); req.setPartitionKeyInternal(partitionKey); } if(options.getStartDateTime() != null){ String dateTimeInHttpFormat = Utils.zonedDateTimeAsUTCRFC1123(options.getStartDateTime().atOffset(ZoneOffset.UTC)); headers.put(HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, dateTimeInHttpFormat); } if (options.getPartitionKeyRangeId() != null) { req.routeTo(new PartitionKeyRangeIdentity(this.options.getPartitionKeyRangeId())); } return req; }
class ChangeFeedQueryImpl<T extends Resource> { private static final String IfNonMatchAllHeaderValue = "*"; private final RxDocumentClientImpl client; private final ResourceType resourceType; private final Class<T> klass; private final String documentsLink; private final ChangeFeedOptions options; public ChangeFeedQueryImpl(RxDocumentClientImpl client, ResourceType resourceType, Class<T> klass, String collectionLink, ChangeFeedOptions changeFeedOptions) { this.client = client; this.resourceType = resourceType; this.klass = klass; this.documentsLink = Utils.joinPath(collectionLink, Paths.DOCUMENTS_PATH_SEGMENT); changeFeedOptions = changeFeedOptions != null ? changeFeedOptions: new ChangeFeedOptions(); if (resourceType.isPartitioned() && changeFeedOptions.getPartitionKeyRangeId() == null && changeFeedOptions.getPartitionKey() == null) { throw new IllegalArgumentException(RMResources.PartitionKeyRangeIdOrPartitionKeyMustBeSpecified); } if (changeFeedOptions.getPartitionKey() != null && !Strings.isNullOrEmpty(changeFeedOptions.getPartitionKeyRangeId())) { throw new IllegalArgumentException(String.format( RMResources.PartitionKeyAndParitionKeyRangeIdBothSpecified , "feedOptions")); } String initialNextIfNoneMatch = null; boolean canUseStartFromBeginning = true; if (changeFeedOptions.getRequestContinuation() != null) { initialNextIfNoneMatch = changeFeedOptions.getRequestContinuation(); canUseStartFromBeginning = false; } if(changeFeedOptions.getStartDateTime() != null){ canUseStartFromBeginning = false; } if (canUseStartFromBeginning && !changeFeedOptions.isStartFromBeginning()) { initialNextIfNoneMatch = IfNonMatchAllHeaderValue; } this.options = getChangeFeedOptions(changeFeedOptions, initialNextIfNoneMatch); } private ChangeFeedOptions getChangeFeedOptions(ChangeFeedOptions options, String continuationToken) { ChangeFeedOptions newOps = new ChangeFeedOptions(options); newOps.setRequestContinuation(continuationToken); return newOps; } public Flux<FeedResponse<T>> executeAsync() { BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = this::createDocumentServiceRequest; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = this::executeRequestAsync; return Paginator.getPaginatedChangeFeedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, options.getMaxItemCount() != null ? options.getMaxItemCount(): -1); } private Mono<FeedResponse<T>> executeRequestAsync(RxDocumentServiceRequest request) { return client.readFeed(request) .map( rsp -> BridgeInternal.toChangeFeedResponsePage(rsp, klass)); } }
class ChangeFeedQueryImpl<T extends Resource> { private static final String IfNonMatchAllHeaderValue = "*"; private final RxDocumentClientImpl client; private final ResourceType resourceType; private final Class<T> klass; private final String documentsLink; private final ChangeFeedOptions options; public ChangeFeedQueryImpl(RxDocumentClientImpl client, ResourceType resourceType, Class<T> klass, String collectionLink, ChangeFeedOptions changeFeedOptions) { this.client = client; this.resourceType = resourceType; this.klass = klass; this.documentsLink = Utils.joinPath(collectionLink, Paths.DOCUMENTS_PATH_SEGMENT); changeFeedOptions = changeFeedOptions != null ? changeFeedOptions: new ChangeFeedOptions(); if (resourceType.isPartitioned() && changeFeedOptions.getPartitionKeyRangeId() == null && changeFeedOptions.getPartitionKey() == null) { throw new IllegalArgumentException(RMResources.PartitionKeyRangeIdOrPartitionKeyMustBeSpecified); } if (changeFeedOptions.getPartitionKey() != null && !Strings.isNullOrEmpty(changeFeedOptions.getPartitionKeyRangeId())) { throw new IllegalArgumentException(String.format( RMResources.PartitionKeyAndParitionKeyRangeIdBothSpecified , "feedOptions")); } String initialNextIfNoneMatch = null; boolean canUseStartFromBeginning = true; if (changeFeedOptions.getRequestContinuation() != null) { initialNextIfNoneMatch = changeFeedOptions.getRequestContinuation(); canUseStartFromBeginning = false; } if(changeFeedOptions.getStartDateTime() != null){ canUseStartFromBeginning = false; } if (canUseStartFromBeginning && !changeFeedOptions.isStartFromBeginning()) { initialNextIfNoneMatch = IfNonMatchAllHeaderValue; } this.options = getChangeFeedOptions(changeFeedOptions, initialNextIfNoneMatch); } private ChangeFeedOptions getChangeFeedOptions(ChangeFeedOptions options, String continuationToken) { ChangeFeedOptions newOps = new ChangeFeedOptions(options); newOps.setRequestContinuation(continuationToken); return newOps; } public Flux<FeedResponse<T>> executeAsync() { BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = this::createDocumentServiceRequest; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = this::executeRequestAsync; return Paginator.getPaginatedChangeFeedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, options.getMaxItemCount() != null ? options.getMaxItemCount(): -1); } private Mono<FeedResponse<T>> executeRequestAsync(RxDocumentServiceRequest request) { return client.readFeed(request) .map( rsp -> BridgeInternal.toChangeFeedResponsePage(rsp, klass)); } }
Does Search offer anonymous access? I thought a key would always need to be set.
public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); }
if (keyCredential != null) {
public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
Do we normally add the `User-Agent` at the end of the pipeline? I thought this normally was added when setting the request ID since it'll be static throughout the request/requests (if retried) being made.
public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); }
httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion,
public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
Should update the exception message here as `null` with throw a different exception.
public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; }
new IllegalArgumentException("'keyCredential' cannot have a null or empty API key."));
public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); } /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); } /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
Should we look into updating other methods which use `Objects.requireNonNull` to log their error?
public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; }
if (keyCredential == null) {
public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); } /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); } /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
Missed the comments here. Will address these in a new PR.
public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); }
if (keyCredential != null) {
public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
https://github.com/Azure/azure-sdk-for-java/pull/11497
public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); }
if (keyCredential != null) {
public SearchAsyncClient buildAsyncClient() { Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPipelinePolicies.add(new AddDatePolicy()); if (keyCredential != null) { this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); } httpPipelinePolicies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline buildPipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
class SearchClientBuilder { private static final String API_KEY = "api-key"; /* * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the * request sent to the response. */ private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); private final List<HttpPipelinePolicy> policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); private final String clientName; private final String clientVersion; private AzureKeyCredential keyCredential; private SearchServiceVersion serviceVersion; private String endpoint; private HttpClient httpClient; private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; private String indexName; private RetryPolicy retryPolicy; /** * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} * and {@link SearchAsyncClient SearchAsyncClients}. */ public SearchClientBuilder() { Map<String, String> properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link SearchClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ public SearchClient buildClient() { return new SearchClient(buildAsyncClient()); } /** * Creates a {@link SearchAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link SearchAsyncClient} is created. * <p> * If {@link * endpoint}, and {@link * All other builder settings are ignored. * * @return A SearchClient with the options set from the builder. * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. */ /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ public SearchClientBuilder endpoint(String endpoint) { 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 AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential */ public SearchClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } /** * Sets the name of the index. * * @param indexName Name of the index. * @return The updated SearchClientBuilder object. * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. */ public SearchClientBuilder indexName(String indexName) { if (CoreUtils.isNullOrEmpty(indexName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); } this.indexName = indexName; return this; } /** * Sets the logging configuration for HTTP requests and responses. * <p> * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Adds a pipeline policy to apply to each request sent. * <p> * This method may be called multiple times, each time it is called the policy will be added to the end of added * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. * @return The updated SearchClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } /** * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * {@link * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store that will be used. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. * <p> * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link SearchServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, {@link SearchServiceVersion * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. * @return The updated SearchClientBuilder object. */ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } }
Would we want to use a parallelization that is more idiomatic to the Storage service usage? I know `Queues.SMALL_BUFFER_SIZE` aligns more with Reactor's usage but could the higher level of parallelization get use into issues.
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null, null) : other; if (other.getBlockSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.blockSize", other.getBlockSize(), 1, MAX_APPEND_FILE_BYTES); } if (other.getMaxSingleUploadSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.maxSingleUploadSize", other.getMaxSingleUploadSize(), 1, MAX_APPEND_FILE_BYTES); } return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(FILE_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(FILE_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(MAX_APPEND_FILE_BYTES) : other.getMaxSingleUploadSize(), other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency()); }
other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency());
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null, null) : other; if (other.getBlockSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.blockSize", other.getBlockSize(), 1, MAX_APPEND_FILE_BYTES); } if (other.getMaxSingleUploadSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.maxSingleUploadSize", other.getMaxSingleUploadSize(), 1, MAX_APPEND_FILE_BYTES); } return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(FILE_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getMaxConcurrency() == null ? Integer.valueOf(FILE_DEFAULT_NUMBER_OF_BUFFERS) : other.getMaxConcurrency(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(MAX_APPEND_FILE_BYTES) : other.getMaxSingleUploadSize()); }
class ModelHelper { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ private static final int MAX_APPEND_FILE_BYTES = 100 * Constants.MB; /** * The block size to use if none is specified in parallel operations. */ private static final int FILE_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB; /** * The number of buffers to use if none is specified on the buffered upload method. */ private static final int FILE_DEFAULT_NUMBER_OF_BUFFERS = 8; /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ }
class ModelHelper { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ private static final int MAX_APPEND_FILE_BYTES = 100 * Constants.MB; /** * The block size to use if none is specified in parallel operations. */ private static final int FILE_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB; /** * The number of buffers to use if none is specified on the buffered upload method. */ private static final int FILE_DEFAULT_NUMBER_OF_BUFFERS = 8; /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ }
Same comment about what the default should be.
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize(), other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency()); }
other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency());
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getMaxConcurrency() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getMaxConcurrency(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize()); }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: } /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ /** * Transforms a blob type into a common type. * @param blobOptions {@link ParallelTransferOptions} * @return {@link com.azure.storage.common.ParallelTransferOptions} */ public static com.azure.storage.common.ParallelTransferOptions wrapBlobOptions( ParallelTransferOptions blobOptions) { Integer blockSize = blobOptions.getBlockSize(); Integer numBuffers = blobOptions.getNumBuffers(); com.azure.storage.common.ProgressReceiver wrappedReceiver = blobOptions.getProgressReceiver() == null ? null : blobOptions.getProgressReceiver()::reportProgress; Integer maxSingleUploadSize = blobOptions.getMaxSingleUploadSize(); return new com.azure.storage.common.ParallelTransferOptions(blockSize, numBuffers, wrappedReceiver, maxSingleUploadSize); } }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: } /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ /** * Transforms a blob type into a common type. * @param blobOptions {@link ParallelTransferOptions} * @return {@link com.azure.storage.common.ParallelTransferOptions} */ public static com.azure.storage.common.ParallelTransferOptions wrapBlobOptions( ParallelTransferOptions blobOptions) { Integer blockSize = blobOptions.getBlockSize(); Integer numBuffers = blobOptions.getMaxConcurrency(); com.azure.storage.common.ProgressReceiver wrappedReceiver = blobOptions.getProgressReceiver() == null ? null : blobOptions.getProgressReceiver()::reportProgress; Integer maxSingleUploadSize = blobOptions.getMaxSingleUploadSize(); return new com.azure.storage.common.ParallelTransferOptions(blockSize, numBuffers, wrappedReceiver, maxSingleUploadSize); } }
Fair point. It is true that accepting this default is what hurt one the customer who filed the issue and why we're making this change. But that also seems like a fairly rare case so far? And I'm not sure what a more idiomatic value for Storage would be. It feels like anything we choose would just be a guess.
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null, null) : other; if (other.getBlockSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.blockSize", other.getBlockSize(), 1, MAX_APPEND_FILE_BYTES); } if (other.getMaxSingleUploadSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.maxSingleUploadSize", other.getMaxSingleUploadSize(), 1, MAX_APPEND_FILE_BYTES); } return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(FILE_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(FILE_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(MAX_APPEND_FILE_BYTES) : other.getMaxSingleUploadSize(), other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency()); }
other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency());
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null, null) : other; if (other.getBlockSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.blockSize", other.getBlockSize(), 1, MAX_APPEND_FILE_BYTES); } if (other.getMaxSingleUploadSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.maxSingleUploadSize", other.getMaxSingleUploadSize(), 1, MAX_APPEND_FILE_BYTES); } return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(FILE_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getMaxConcurrency() == null ? Integer.valueOf(FILE_DEFAULT_NUMBER_OF_BUFFERS) : other.getMaxConcurrency(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(MAX_APPEND_FILE_BYTES) : other.getMaxSingleUploadSize()); }
class ModelHelper { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ private static final int MAX_APPEND_FILE_BYTES = 100 * Constants.MB; /** * The block size to use if none is specified in parallel operations. */ private static final int FILE_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB; /** * The number of buffers to use if none is specified on the buffered upload method. */ private static final int FILE_DEFAULT_NUMBER_OF_BUFFERS = 8; /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ }
class ModelHelper { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ private static final int MAX_APPEND_FILE_BYTES = 100 * Constants.MB; /** * The block size to use if none is specified in parallel operations. */ private static final int FILE_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB; /** * The number of buffers to use if none is specified on the buffered upload method. */ private static final int FILE_DEFAULT_NUMBER_OF_BUFFERS = 8; /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ }
https://github.com/reactor/reactor-core/blob/6058a391f614de6213fb85970272fc5b342bd181/reactor-core/src/main/java/reactor/util/concurrent/Queues.java#L88 Looks like that'd be 256 by default. Pretty high. We limit number of buffers. Shouldn't max concurrency == numBuffers ? Or maxConcurrency be <= numbBuffers with numBuffers being default ?
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize(), other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency()); }
other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency());
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getMaxConcurrency() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getMaxConcurrency(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize()); }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: } /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ /** * Transforms a blob type into a common type. * @param blobOptions {@link ParallelTransferOptions} * @return {@link com.azure.storage.common.ParallelTransferOptions} */ public static com.azure.storage.common.ParallelTransferOptions wrapBlobOptions( ParallelTransferOptions blobOptions) { Integer blockSize = blobOptions.getBlockSize(); Integer numBuffers = blobOptions.getNumBuffers(); com.azure.storage.common.ProgressReceiver wrappedReceiver = blobOptions.getProgressReceiver() == null ? null : blobOptions.getProgressReceiver()::reportProgress; Integer maxSingleUploadSize = blobOptions.getMaxSingleUploadSize(); return new com.azure.storage.common.ParallelTransferOptions(blockSize, numBuffers, wrappedReceiver, maxSingleUploadSize); } }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: } /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ /** * Transforms a blob type into a common type. * @param blobOptions {@link ParallelTransferOptions} * @return {@link com.azure.storage.common.ParallelTransferOptions} */ public static com.azure.storage.common.ParallelTransferOptions wrapBlobOptions( ParallelTransferOptions blobOptions) { Integer blockSize = blobOptions.getBlockSize(); Integer numBuffers = blobOptions.getMaxConcurrency(); com.azure.storage.common.ProgressReceiver wrappedReceiver = blobOptions.getProgressReceiver() == null ? null : blobOptions.getProgressReceiver()::reportProgress; Integer maxSingleUploadSize = blobOptions.getMaxSingleUploadSize(); return new com.azure.storage.common.ParallelTransferOptions(blockSize, numBuffers, wrappedReceiver, maxSingleUploadSize); } }
https://github.com/reactor/reactor-core/blob/6058a391f614de6213fb85970272fc5b342bd181/reactor-core/src/main/java/reactor/util/concurrent/Queues.java#L88 Looks like that'd be 256 by default. Pretty high. We limit number of buffers. Shouldn't max concurrency == numBuffers ? Or maxConcurrency be <= numbBuffers with numBuffers being default ?
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null, null) : other; if (other.getBlockSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.blockSize", other.getBlockSize(), 1, MAX_APPEND_FILE_BYTES); } if (other.getMaxSingleUploadSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.maxSingleUploadSize", other.getMaxSingleUploadSize(), 1, MAX_APPEND_FILE_BYTES); } return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(FILE_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(FILE_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(MAX_APPEND_FILE_BYTES) : other.getMaxSingleUploadSize(), other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency()); }
other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency());
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null, null) : other; if (other.getBlockSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.blockSize", other.getBlockSize(), 1, MAX_APPEND_FILE_BYTES); } if (other.getMaxSingleUploadSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.maxSingleUploadSize", other.getMaxSingleUploadSize(), 1, MAX_APPEND_FILE_BYTES); } return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(FILE_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getMaxConcurrency() == null ? Integer.valueOf(FILE_DEFAULT_NUMBER_OF_BUFFERS) : other.getMaxConcurrency(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(MAX_APPEND_FILE_BYTES) : other.getMaxSingleUploadSize()); }
class ModelHelper { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ private static final int MAX_APPEND_FILE_BYTES = 100 * Constants.MB; /** * The block size to use if none is specified in parallel operations. */ private static final int FILE_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB; /** * The number of buffers to use if none is specified on the buffered upload method. */ private static final int FILE_DEFAULT_NUMBER_OF_BUFFERS = 8; /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ }
class ModelHelper { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ private static final int MAX_APPEND_FILE_BYTES = 100 * Constants.MB; /** * The block size to use if none is specified in parallel operations. */ private static final int FILE_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB; /** * The number of buffers to use if none is specified on the buffered upload method. */ private static final int FILE_DEFAULT_NUMBER_OF_BUFFERS = 8; /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ }
I don't think we should set them to equal because numBuffers isn't used in every parallel operation, so it's not quite the same. 256 does sound high, but again we haven't seen OOM errors before even with this default. On the other hand, it's probably better to err on the side of being a little slower than running out of memory...
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize(), other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency()); }
other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency());
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getMaxConcurrency() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getMaxConcurrency(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize()); }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: } /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ /** * Transforms a blob type into a common type. * @param blobOptions {@link ParallelTransferOptions} * @return {@link com.azure.storage.common.ParallelTransferOptions} */ public static com.azure.storage.common.ParallelTransferOptions wrapBlobOptions( ParallelTransferOptions blobOptions) { Integer blockSize = blobOptions.getBlockSize(); Integer numBuffers = blobOptions.getNumBuffers(); com.azure.storage.common.ProgressReceiver wrappedReceiver = blobOptions.getProgressReceiver() == null ? null : blobOptions.getProgressReceiver()::reportProgress; Integer maxSingleUploadSize = blobOptions.getMaxSingleUploadSize(); return new com.azure.storage.common.ParallelTransferOptions(blockSize, numBuffers, wrappedReceiver, maxSingleUploadSize); } }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: } /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ /** * Transforms a blob type into a common type. * @param blobOptions {@link ParallelTransferOptions} * @return {@link com.azure.storage.common.ParallelTransferOptions} */ public static com.azure.storage.common.ParallelTransferOptions wrapBlobOptions( ParallelTransferOptions blobOptions) { Integer blockSize = blobOptions.getBlockSize(); Integer numBuffers = blobOptions.getMaxConcurrency(); com.azure.storage.common.ProgressReceiver wrappedReceiver = blobOptions.getProgressReceiver() == null ? null : blobOptions.getProgressReceiver()::reportProgress; Integer maxSingleUploadSize = blobOptions.getMaxSingleUploadSize(); return new com.azure.storage.common.ParallelTransferOptions(blockSize, numBuffers, wrappedReceiver, maxSingleUploadSize); } }
In v10/11 we defaulted to 5. It was completely arbitrary, but how does that sound here?
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize(), other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency()); }
other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency());
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getMaxConcurrency() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getMaxConcurrency(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize()); }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: } /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ /** * Transforms a blob type into a common type. * @param blobOptions {@link ParallelTransferOptions} * @return {@link com.azure.storage.common.ParallelTransferOptions} */ public static com.azure.storage.common.ParallelTransferOptions wrapBlobOptions( ParallelTransferOptions blobOptions) { Integer blockSize = blobOptions.getBlockSize(); Integer numBuffers = blobOptions.getNumBuffers(); com.azure.storage.common.ProgressReceiver wrappedReceiver = blobOptions.getProgressReceiver() == null ? null : blobOptions.getProgressReceiver()::reportProgress; Integer maxSingleUploadSize = blobOptions.getMaxSingleUploadSize(); return new com.azure.storage.common.ParallelTransferOptions(blockSize, numBuffers, wrappedReceiver, maxSingleUploadSize); } }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: } /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ /** * Transforms a blob type into a common type. * @param blobOptions {@link ParallelTransferOptions} * @return {@link com.azure.storage.common.ParallelTransferOptions} */ public static com.azure.storage.common.ParallelTransferOptions wrapBlobOptions( ParallelTransferOptions blobOptions) { Integer blockSize = blobOptions.getBlockSize(); Integer numBuffers = blobOptions.getMaxConcurrency(); com.azure.storage.common.ProgressReceiver wrappedReceiver = blobOptions.getProgressReceiver() == null ? null : blobOptions.getProgressReceiver()::reportProgress; Integer maxSingleUploadSize = blobOptions.getMaxSingleUploadSize(); return new com.azure.storage.common.ParallelTransferOptions(blockSize, numBuffers, wrappedReceiver, maxSingleUploadSize); } }
result validation validates page size, etc. that may fail. you need to update the validation section.
public void readUserDefinedFunctions() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosUserDefinedFunctionProperties> feedObservable = createdCollection.getScripts() .readAllUserDefinedFunctions(); int expectedPageSize = (createdUserDefinedFunctions.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserDefinedFunctionProperties> validator = new FeedResponseListValidator.Builder<CosmosUserDefinedFunctionProperties>() .totalSize(createdUserDefinedFunctions.size()) .exactlyContainsInAnyOrder( createdUserDefinedFunctions.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<CosmosUserDefinedFunctionProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
.readAllUserDefinedFunctions();
public void readUserDefinedFunctions() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosUserDefinedFunctionProperties> feedObservable = createdCollection.getScripts() .readAllUserDefinedFunctions(); int expectedPageSize = (createdUserDefinedFunctions.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserDefinedFunctionProperties> validator = new FeedResponseListValidator.Builder<CosmosUserDefinedFunctionProperties>() .totalSize(createdUserDefinedFunctions.size()) .exactlyContainsInAnyOrder( createdUserDefinedFunctions.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<CosmosUserDefinedFunctionProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
class ReadFeedUdfsTest extends TestSuiteBase { private Database createdDatabase; private CosmosAsyncContainer createdCollection; private List<CosmosUserDefinedFunctionProperties> createdUserDefinedFunctions = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedUdfsTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedUdfsTest() { client = getClientBuilder().buildAsyncClient(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); for (int i = 0; i < 5; i++) { createdUserDefinedFunctions.add(createUserDefinedFunctions(createdCollection)); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } public CosmosUserDefinedFunctionProperties createUserDefinedFunctions(CosmosAsyncContainer cosmosContainer) { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return cosmosContainer.getScripts().createUserDefinedFunction(udf).block() .getProperties(); } private String getCollectionLink() { return "dbs/" + getDatabaseId() + "/colls/" + getCollectionId(); } private String getCollectionId() { return createdCollection.getId(); } private String getDatabaseId() { return createdDatabase.getId(); } }
class ReadFeedUdfsTest extends TestSuiteBase { private Database createdDatabase; private CosmosAsyncContainer createdCollection; private List<CosmosUserDefinedFunctionProperties> createdUserDefinedFunctions = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedUdfsTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedUdfsTest() { client = getClientBuilder().buildAsyncClient(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); for (int i = 0; i < 5; i++) { createdUserDefinedFunctions.add(createUserDefinedFunctions(createdCollection)); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } public CosmosUserDefinedFunctionProperties createUserDefinedFunctions(CosmosAsyncContainer cosmosContainer) { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return cosmosContainer.getScripts().createUserDefinedFunction(udf).block() .getProperties(); } private String getCollectionLink() { return "dbs/" + getDatabaseId() + "/colls/" + getCollectionId(); } private String getCollectionId() { return createdCollection.getId(); } private String getDatabaseId() { return createdDatabase.getId(); } }
result validation validates page size, etc. that may fail. you need to update the validation section.
public void readUsers() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosUserProperties> feedObservable = createdDatabase.readAllUsers(); int expectedPageSize = (createdUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(createdUsers.size()) .exactlyContainsInAnyOrder(createdUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
int expectedPageSize = (createdUsers.size() + maxItemCount - 1) / maxItemCount;
public void readUsers() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosUserProperties> feedObservable = createdDatabase.readAllUsers(); int expectedPageSize = (createdUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(createdUsers.size()) .exactlyContainsInAnyOrder(createdUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
class ReadFeedUsersTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncDatabase createdDatabase; private CosmosAsyncClient client; private List<CosmosUserProperties> createdUsers = new ArrayList<>(); @Factory(dataProvider = "clientBuilders") public ReadFeedUsersTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedUsersTest() { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { createdUsers.add(createUsers(createdDatabase)); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } public CosmosUserProperties createUsers(CosmosAsyncDatabase cosmosDatabase) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); return cosmosDatabase.createUser(user).block().getProperties(); } }
class ReadFeedUsersTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncDatabase createdDatabase; private CosmosAsyncClient client; private List<CosmosUserProperties> createdUsers = new ArrayList<>(); @Factory(dataProvider = "clientBuilders") public ReadFeedUsersTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedUsersTest() { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { createdUsers.add(createUsers(createdDatabase)); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } public CosmosUserProperties createUsers(CosmosAsyncDatabase cosmosDatabase) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); return cosmosDatabase.createUser(user).block().getProperties(); } }
the page size validation may fail. ```java int expectedPageSize = (allDatabases.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosDatabaseProperties> validator = new FeedResponseListValidator.Builder<CosmosDatabaseProperties>() .totalSize(allDatabases.size()) .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosDatabaseProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); ```
public void readDatabases() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosDatabaseProperties> feedObservable = client.readAllDatabases(); int expectedPageSize = (allDatabases.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosDatabaseProperties> validator = new FeedResponseListValidator.Builder<CosmosDatabaseProperties>() .totalSize(allDatabases.size()) .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosDatabaseProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
int expectedPageSize = (allDatabases.size() + maxItemCount - 1) / maxItemCount;
public void readDatabases() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosDatabaseProperties> feedObservable = client.readAllDatabases(); int expectedPageSize = (allDatabases.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosDatabaseProperties> validator = new FeedResponseListValidator.Builder<CosmosDatabaseProperties>() .totalSize(allDatabases.size()) .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosDatabaseProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
class ReadFeedDatabasesTest extends TestSuiteBase { private List<CosmosDatabaseProperties> createdDatabases = new ArrayList<>(); private List<CosmosDatabaseProperties> allDatabases = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuilders") public ReadFeedDatabasesTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedDatabasesTest() throws URISyntaxException { client = getClientBuilder().buildAsyncClient(); allDatabases = client.readAllDatabases() .collectList() .block(); for(int i = 0; i < 5; i++) { createdDatabases.add(createDatabase(client)); } allDatabases.addAll(createdDatabases); } public CosmosDatabaseProperties createDatabase(CosmosAsyncClient client) { CosmosDatabaseProperties db = new CosmosDatabaseProperties(UUID.randomUUID().toString()); return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().getProperties(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { for (int i = 0; i < 5; i ++) { safeDeleteDatabase(client.getDatabase(createdDatabases.get(i).getId())); } safeClose(client); } }
class ReadFeedDatabasesTest extends TestSuiteBase { private List<CosmosDatabaseProperties> createdDatabases = new ArrayList<>(); private List<CosmosDatabaseProperties> allDatabases = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuilders") public ReadFeedDatabasesTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedDatabasesTest() throws URISyntaxException { client = getClientBuilder().buildAsyncClient(); allDatabases = client.readAllDatabases() .collectList() .block(); for(int i = 0; i < 5; i++) { createdDatabases.add(createDatabase(client)); } allDatabases.addAll(createdDatabases); } public CosmosDatabaseProperties createDatabase(CosmosAsyncClient client) { CosmosDatabaseProperties db = new CosmosDatabaseProperties(UUID.randomUUID().toString()); return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().getProperties(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { for (int i = 0; i < 5; i ++) { safeDeleteDatabase(client.getDatabase(createdDatabases.get(i).getId())); } safeClose(client); } }
I'm not seeing any test failures when run locally... I'm not sure I understand the concern since we already moved the maxItemCount out of the FeedOptions when we transitioned to return PageFlux results... Plus under the new API we do exactly what the test does, which is to call the now package private readAll*() API with a "new FeedOptions()" argument value.
public void readDatabases() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosDatabaseProperties> feedObservable = client.readAllDatabases(); int expectedPageSize = (allDatabases.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosDatabaseProperties> validator = new FeedResponseListValidator.Builder<CosmosDatabaseProperties>() .totalSize(allDatabases.size()) .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosDatabaseProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
int expectedPageSize = (allDatabases.size() + maxItemCount - 1) / maxItemCount;
public void readDatabases() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosDatabaseProperties> feedObservable = client.readAllDatabases(); int expectedPageSize = (allDatabases.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosDatabaseProperties> validator = new FeedResponseListValidator.Builder<CosmosDatabaseProperties>() .totalSize(allDatabases.size()) .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosDatabaseProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
class ReadFeedDatabasesTest extends TestSuiteBase { private List<CosmosDatabaseProperties> createdDatabases = new ArrayList<>(); private List<CosmosDatabaseProperties> allDatabases = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuilders") public ReadFeedDatabasesTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedDatabasesTest() throws URISyntaxException { client = getClientBuilder().buildAsyncClient(); allDatabases = client.readAllDatabases() .collectList() .block(); for(int i = 0; i < 5; i++) { createdDatabases.add(createDatabase(client)); } allDatabases.addAll(createdDatabases); } public CosmosDatabaseProperties createDatabase(CosmosAsyncClient client) { CosmosDatabaseProperties db = new CosmosDatabaseProperties(UUID.randomUUID().toString()); return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().getProperties(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { for (int i = 0; i < 5; i ++) { safeDeleteDatabase(client.getDatabase(createdDatabases.get(i).getId())); } safeClose(client); } }
class ReadFeedDatabasesTest extends TestSuiteBase { private List<CosmosDatabaseProperties> createdDatabases = new ArrayList<>(); private List<CosmosDatabaseProperties> allDatabases = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuilders") public ReadFeedDatabasesTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedDatabasesTest() throws URISyntaxException { client = getClientBuilder().buildAsyncClient(); allDatabases = client.readAllDatabases() .collectList() .block(); for(int i = 0; i < 5; i++) { createdDatabases.add(createDatabase(client)); } allDatabases.addAll(createdDatabases); } public CosmosDatabaseProperties createDatabase(CosmosAsyncClient client) { CosmosDatabaseProperties db = new CosmosDatabaseProperties(UUID.randomUUID().toString()); return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().getProperties(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { for (int i = 0; i < 5; i ++) { safeDeleteDatabase(client.getDatabase(createdDatabases.get(i).getId())); } safeClose(client); } }
Page sizes are controlled by maxItemCount which is no longer part of the FeedOptions since when we start returning PageFlux as results.
public void readUsers() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosUserProperties> feedObservable = createdDatabase.readAllUsers(); int expectedPageSize = (createdUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(createdUsers.size()) .exactlyContainsInAnyOrder(createdUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
int expectedPageSize = (createdUsers.size() + maxItemCount - 1) / maxItemCount;
public void readUsers() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosUserProperties> feedObservable = createdDatabase.readAllUsers(); int expectedPageSize = (createdUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(createdUsers.size()) .exactlyContainsInAnyOrder(createdUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
class ReadFeedUsersTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncDatabase createdDatabase; private CosmosAsyncClient client; private List<CosmosUserProperties> createdUsers = new ArrayList<>(); @Factory(dataProvider = "clientBuilders") public ReadFeedUsersTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedUsersTest() { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { createdUsers.add(createUsers(createdDatabase)); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } public CosmosUserProperties createUsers(CosmosAsyncDatabase cosmosDatabase) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); return cosmosDatabase.createUser(user).block().getProperties(); } }
class ReadFeedUsersTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncDatabase createdDatabase; private CosmosAsyncClient client; private List<CosmosUserProperties> createdUsers = new ArrayList<>(); @Factory(dataProvider = "clientBuilders") public ReadFeedUsersTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedUsersTest() { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { createdUsers.add(createUsers(createdDatabase)); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } public CosmosUserProperties createUsers(CosmosAsyncDatabase cosmosDatabase) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); return cosmosDatabase.createUser(user).block().getProperties(); } }
Page sizes are controlled by maxItemCount which is no longer part of the FeedOptions since when we start returning PageFlux as results.
public void readUserDefinedFunctions() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosUserDefinedFunctionProperties> feedObservable = createdCollection.getScripts() .readAllUserDefinedFunctions(); int expectedPageSize = (createdUserDefinedFunctions.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserDefinedFunctionProperties> validator = new FeedResponseListValidator.Builder<CosmosUserDefinedFunctionProperties>() .totalSize(createdUserDefinedFunctions.size()) .exactlyContainsInAnyOrder( createdUserDefinedFunctions.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<CosmosUserDefinedFunctionProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
.readAllUserDefinedFunctions();
public void readUserDefinedFunctions() throws Exception { int maxItemCount = 2; CosmosPagedFlux<CosmosUserDefinedFunctionProperties> feedObservable = createdCollection.getScripts() .readAllUserDefinedFunctions(); int expectedPageSize = (createdUserDefinedFunctions.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserDefinedFunctionProperties> validator = new FeedResponseListValidator.Builder<CosmosUserDefinedFunctionProperties>() .totalSize(createdUserDefinedFunctions.size()) .exactlyContainsInAnyOrder( createdUserDefinedFunctions.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder<CosmosUserDefinedFunctionProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable.byPage(maxItemCount), validator, FEED_TIMEOUT); }
class ReadFeedUdfsTest extends TestSuiteBase { private Database createdDatabase; private CosmosAsyncContainer createdCollection; private List<CosmosUserDefinedFunctionProperties> createdUserDefinedFunctions = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedUdfsTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedUdfsTest() { client = getClientBuilder().buildAsyncClient(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); for (int i = 0; i < 5; i++) { createdUserDefinedFunctions.add(createUserDefinedFunctions(createdCollection)); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } public CosmosUserDefinedFunctionProperties createUserDefinedFunctions(CosmosAsyncContainer cosmosContainer) { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return cosmosContainer.getScripts().createUserDefinedFunction(udf).block() .getProperties(); } private String getCollectionLink() { return "dbs/" + getDatabaseId() + "/colls/" + getCollectionId(); } private String getCollectionId() { return createdCollection.getId(); } private String getDatabaseId() { return createdDatabase.getId(); } }
class ReadFeedUdfsTest extends TestSuiteBase { private Database createdDatabase; private CosmosAsyncContainer createdCollection; private List<CosmosUserDefinedFunctionProperties> createdUserDefinedFunctions = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedUdfsTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_ReadFeedUdfsTest() { client = getClientBuilder().buildAsyncClient(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); for (int i = 0; i < 5; i++) { createdUserDefinedFunctions.add(createUserDefinedFunctions(createdCollection)); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } public CosmosUserDefinedFunctionProperties createUserDefinedFunctions(CosmosAsyncContainer cosmosContainer) { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return cosmosContainer.getScripts().createUserDefinedFunction(udf).block() .getProperties(); } private String getCollectionLink() { return "dbs/" + getDatabaseId() + "/colls/" + getCollectionId(); } private String getCollectionId() { return createdCollection.getId(); } private String getDatabaseId() { return createdDatabase.getId(); } }
We are replacing `getResourceId()` -> with `getId()` Can you please make sure these tests pass ? Here and everywhere else in your changes ?
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
.exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList()))
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
Please don't replace this in the tests. ResourceId is a unique value, however id may not necessary be unique. To access package private getResource you can use BridgeInternal if needed. please roll back these changes.
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
.exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList()))
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
So basically what this comes to is that UUID.randomUUID().toString() does not generate unique IDs??? If yes than we have a bigger problem through the whole test bed.
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
.exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList()))
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
Milis, are you taking into account that ID may not necessarily be unique across multiple partitions?
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
.exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList()))
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
The IDs for all those tests are generated using the API I just mentioned; they pretty much should be unique as they come out from it. The second thing is that there are no partition setting that are applicable to databases, containers, container scripts for instance. All these tests use the IDs to count the results (see Reactor collect() call following them). So unless we have a special test that create a batch of documents and they all inserted in two or more sets with different partition key values, we should be fine. I'm running the full set of tests; that should give us the validation we need, right?
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
.exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList()))
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
@milismsft as the goal of the PR is to change the public api, I suggest we don't change how tests work. If you have thought on improving the tests please consider anything other than public api change outside of the PR for public api change. as a pattern we rely on resourceId to ensure we cover having same id across multiple partition scenario.
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
.exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList()))
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
`FeedResponseListValidator.exactlyContainsInAnyOrder` uses resourceId internally for validation. now on your side you are passing Id and on the other side it compares against resoruceId, I suspect the tests will fail. if you don't want to go with BridgeInternal approach for non-partitioned resources please use `FeedResponseListValidator.containsExactlyIds` and please make sure the tests after this change pass.
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
.exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList()))
public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); int maxItemCount = 2; String databaseLink = TestUtils.getDatabaseNameLink(databaseId); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); private List<CosmosUserProperties> createdUsers = new ArrayList<>(); private CosmosAsyncClient client; private CosmosAsyncDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { String filterUserId = createdUsers.get(0).getId(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); int maxItemCount = 5; CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); List<CosmosUserProperties> expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + maxItemCount - 1) / maxItemCount; FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .totalSize(expectedUsers.size()) .exactlyContainsIdsInAnyOrder(expectedUsers.stream().map(CosmosUserProperties::getId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(maxItemCount), validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); CosmosPagedFlux<CosmosUserProperties> queryObservable = createdDatabase.queryUsers(query, options); FeedResponseListValidator<CosmosUserProperties> validator = new FeedResponseListValidator.Builder<CosmosUserProperties>() .containsExactly(new ArrayList<>()) .numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder<CosmosUserProperties>() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable.byPage(), validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_UserQueryTest() throws Exception { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.setId(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().getProperties()); } waitIfNeededForReplicasToCatchUp(getClientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(createdDatabase); safeClose(client); } }
```suggestion return OperationKind.DELETE == conflict.getOperationKind()); ```
private boolean isDelete(Conflict conflict) { return StringUtils.equalsIgnoreCase(conflict.getOperationKind().toString(), "delete"); }
return StringUtils.equalsIgnoreCase(conflict.getOperationKind().toString(), "delete");
private boolean isDelete(Conflict conflict) { return OperationKind.DELETE == conflict.getOperationKind(); }
class ConflictWorker { private static Logger logger = LoggerFactory.getLogger(ConflictWorker.class); private final Scheduler schedulerForBlockingWork; private final List<AsyncDocumentClient> clients; private final String basicCollectionUri; private final String manualCollectionUri; private final String lwwCollectionUri; private final String udpCollectionUri; private final String databaseName; private final String basicCollectionName; private final String manualCollectionName; private final String lwwCollectionName; private final String udpCollectionName; private final ExecutorService executor; public ConflictWorker(String databaseName, String basicCollectionName, String manualCollectionName, String lwwCollectionName, String udpCollectionName) { this.clients = new ArrayList<>(); this.basicCollectionUri = Helpers.createDocumentCollectionUri(databaseName, basicCollectionName); this.manualCollectionUri = Helpers.createDocumentCollectionUri(databaseName, manualCollectionName); this.lwwCollectionUri = Helpers.createDocumentCollectionUri(databaseName, lwwCollectionName); this.udpCollectionUri = Helpers.createDocumentCollectionUri(databaseName, udpCollectionName); this.databaseName = databaseName; this.basicCollectionName = basicCollectionName; this.manualCollectionName = manualCollectionName; this.lwwCollectionName = lwwCollectionName; this.udpCollectionName = udpCollectionName; this.executor = Executors.newFixedThreadPool(100); this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public void addClient(AsyncDocumentClient client) { this.clients.add(client); } private DocumentCollection createCollectionIfNotExists(AsyncDocumentClient createClient, String databaseName, DocumentCollection collection) { return Helpers.createCollectionIfNotExists(createClient, this.databaseName, collection) .subscribeOn(schedulerForBlockingWork).block(); } private DocumentCollection createCollectionIfNotExists(AsyncDocumentClient createClient, String databaseName, String collectionName) { return Helpers.createCollectionIfNotExists(createClient, this.databaseName, this.basicCollectionName) .subscribeOn(schedulerForBlockingWork).block(); } private DocumentCollection getCollectionDefForManual(String id) { DocumentCollection collection = new DocumentCollection(); collection.setId(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy(); collection.setConflictResolutionPolicy(policy); return collection; } private DocumentCollection getCollectionDefForLastWinWrites(String id, String conflictResolutionPath) { DocumentCollection collection = new DocumentCollection(); collection.setId(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createLastWriterWinsPolicy(conflictResolutionPath); collection.setConflictResolutionPolicy(policy); return collection; } private DocumentCollection getCollectionDefForCustom(String id, String storedProc) { DocumentCollection collection = new DocumentCollection(); collection.setId(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy(storedProc); collection.setConflictResolutionPolicy(policy); return collection; } public void initialize() throws Exception { AsyncDocumentClient createClient = this.clients.get(0); Helpers.createDatabaseIfNotExists(createClient, this.databaseName).subscribeOn(schedulerForBlockingWork).block(); DocumentCollection basic = createCollectionIfNotExists(createClient, this.databaseName, this.basicCollectionName); DocumentCollection manualCollection = createCollectionIfNotExists(createClient, Helpers.createDatabaseUri(this.databaseName), getCollectionDefForManual(this.manualCollectionName)); DocumentCollection lwwCollection = createCollectionIfNotExists(createClient, Helpers.createDatabaseUri(this.databaseName), getCollectionDefForLastWinWrites(this.lwwCollectionName, "/regionId")); DocumentCollection udpCollection = createCollectionIfNotExists(createClient, Helpers.createDatabaseUri(this.databaseName), getCollectionDefForCustom(this.udpCollectionName, String.format("dbs/%s/colls/%s/sprocs/%s", this.databaseName, this.udpCollectionName, "resolver"))); StoredProcedure lwwSproc = new StoredProcedure(); lwwSproc.setId("resolver"); lwwSproc.setBody(IOUtils.toString( getClass().getClassLoader().getResourceAsStream("resolver-storedproc.txt"), "UTF-8")); lwwSproc = getResource(createClient.upsertStoredProcedure( Helpers.createDocumentCollectionUri(this.databaseName, this.udpCollectionName), lwwSproc, null)); } private <T extends Resource> T getResource(Mono<ResourceResponse<T>> obs) { return obs.subscribeOn(schedulerForBlockingWork).single().block().getResource(); } public void runManualConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnManual(); logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnManual(); logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnManual(); } public void runLWWConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnLWW(); logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnLWW(); logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnLWW(); } public void runUDPConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnUdp(); logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnUdp(); logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnUdp(); } public void runInsertConflictOnManual() throws Exception { do { logger.info("1) Performing conflicting insert across {} regions on {}", this.clients.size(), this.manualCollectionName); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryInsertDocument(client, this.manualCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().subscribeOn(schedulerForBlockingWork).single().block(); if (conflictDocuments.size() == this.clients.size()) { logger.info("2) Caused {} insert conflicts, verifying conflict resolution", conflictDocuments.size()); for (Document conflictingInsert : conflictDocuments) { this.validateManualConflict(this.clients, conflictingInsert); } break; } else { logger.info("Retrying insert to induce conflicts"); } } while (true); } public void runUpdateConflictOnManual() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.manualCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting update across 3 regions on {}", this.manualCollectionName); ArrayList<Mono<Document>> updateTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { updateTask.add(this.tryUpdateDocument(client, this.manualCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(updateTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} updated conflicts, verifying conflict resolution", conflictDocuments.size()); for (Document conflictingUpdate : conflictDocuments) { this.validateManualConflict(this.clients, conflictingUpdate); } break; } else { logger.info("Retrying update to induce conflicts"); } } while (true); } public void runDeleteConflictOnManual() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.manualCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(10); logger.info("1) Performing conflicting delete across 3 regions on {}", this.manualCollectionName); ArrayList<Mono<Document>> deleteTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { deleteTask.add(this.tryDeleteDocument(client, this.manualCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(deleteTask).collectList() .subscribeOn(schedulerForBlockingWork) .single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} delete conflicts, verifying conflict resolution", conflictDocuments.size()); for (Document conflictingDelete : conflictDocuments) { this.validateManualConflict(this.clients, conflictingDelete); } break; } else { logger.info("Retrying update to induce conflicts"); } } while (true); } public void runInsertConflictOnLWW() throws Exception { do { logger.info("Performing conflicting insert across 3 regions"); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryInsertDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("Inserted {} conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateLWW(this.clients, conflictDocuments); break; } else { logger.info("Retrying insert to induce conflicts"); } } while (true); } public void runUpdateConflictOnLWW() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.lwwCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting update across {} regions on {}", this.clients.size(), this.lwwCollectionUri); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryUpdateDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} update conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateLWW(this.clients, conflictDocuments); break; } else { logger.info("Retrying insert to induce conflicts"); } } while (true); } public void runDeleteConflictOnLWW() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.lwwCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting delete across {} regions on {}", this.clients.size(), this.lwwCollectionUri); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { if (index % 2 == 1) { insertTask.add(this.tryDeleteDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } else { insertTask.add(this.tryUpdateDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("Inserted {} conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateLWW(this.clients, conflictDocuments, true); break; } else { logger.info("Retrying update/delete to induce conflicts"); } } while (true); } public void runInsertConflictOnUdp() throws Exception { do { logger.info("1) Performing conflicting insert across 3 regions on {}", this.udpCollectionName); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryInsertDocument(client, this.udpCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} insert conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateUDPAsync(this.clients, conflictDocuments); break; } else { logger.info("Retrying insert to induce conflicts"); } } while (true); } public void runUpdateConflictOnUdp() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.udpCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting update across 3 regions on {}", this.udpCollectionUri); ArrayList<Mono<Document>> updateTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { updateTask.add(this.tryUpdateDocument(client, this.udpCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(updateTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} update conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateUDPAsync(this.clients, conflictDocuments); break; } else { logger.info("Retrying update to induce conflicts"); } } while (true); } public void runDeleteConflictOnUdp() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.udpCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting update/delete across 3 regions on {}", this.udpCollectionUri); ArrayList<Mono<Document>> deleteTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { if (index % 2 == 1) { deleteTask.add(this.tryDeleteDocument(client, this.udpCollectionUri, conflictDocument, index++)); } else { deleteTask.add(this.tryUpdateDocument(client, this.udpCollectionUri, conflictDocument, index++)); } } List<Document> conflictDocuments = Flux.merge(deleteTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} delete conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateUDPAsync(this.clients, conflictDocuments, true); break; } else { logger.info("Retrying update/delete to induce conflicts"); } } while (true); } private Mono<Document> tryInsertDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { logger.debug("region: {}", client.getWriteEndpoint()); BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); return client.createDocument(collectionUri, document, null, false) .onErrorResume(e -> { if (hasDocumentClientException(e, 409)) { return Mono.empty(); } else { return Mono.error(e); } }).map(ResourceResponse::getResource); } private boolean hasDocumentClientException(Throwable e, int statusCode) { if (e instanceof CosmosException) { CosmosException dce = (CosmosException) e; return dce.getStatusCode() == statusCode; } return false; } private boolean hasDocumentClientExceptionCause(Throwable e) { while (e != null) { if (e instanceof CosmosException) { return true; } e = e.getCause(); } return false; } private boolean hasDocumentClientExceptionCause(Throwable e, int statusCode) { while (e != null) { if (e instanceof CosmosException) { CosmosException dce = (CosmosException) e; return dce.getStatusCode() == statusCode; } e = e.getCause(); } return false; } private Mono<Document> tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setIfMatchETag(document.getETag()); return client.replaceDocument(document.getSelfLink(), document, null).onErrorResume(e -> { if (hasDocumentClientException(e, 412)) { return Mono.empty(); } return Mono.error(e); }).map(ResourceResponse::getResource); } private Mono<Document> tryDeleteDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setIfMatchETag(document.getETag()); return client.deleteDocument(document.getSelfLink(), options).onErrorResume(e -> { if (hasDocumentClientException(e, 412)) { return Mono.empty(); } return Mono.error(e); }).map(rr -> document); } private void validateManualConflict(List<AsyncDocumentClient> clients, Document conflictDocument) throws Exception { boolean conflictExists = false; for (AsyncDocumentClient client : clients) { conflictExists = this.validateManualConflict(client, conflictDocument); } if (conflictExists) { this.deleteConflict(conflictDocument); } } private boolean equals(String a, String b) { return StringUtils.equals(a, b); } private boolean validateManualConflict(AsyncDocumentClient client, Document conflictDocument) throws Exception { while (true) { FeedResponse<Conflict> response = client.readConflicts(this.manualCollectionUri, null) .take(1).single().block(); for (Conflict conflict : response.getResults()) { if (!isDelete(conflict)) { Document conflictDocumentContent = conflict.getResource(Document.class); if (equals(conflictDocument.getId(), conflictDocumentContent.getId())) { if (equals(conflictDocument.getResourceId(), conflictDocumentContent.getResourceId()) && equals(conflictDocument.getETag(), conflictDocumentContent.getETag())) { logger.info("Document from Region {} lost conflict @ {}", conflictDocument.getId(), conflictDocument.getInt("regionId"), client.getReadEndpoint()); return true; } else { try { Document winnerDocument = client.readDocument(conflictDocument.getSelfLink(), null) .single().block().getResource(); logger.info("Document from region {} won the conflict @ {}", conflictDocument.getInt("regionId"), client.getReadEndpoint()); return false; } catch (Exception exception) { if (hasDocumentClientException(exception, 404)) { throw exception; } else { logger.info( "Document from region {} not found @ {}", conflictDocument.getInt("regionId"), client.getReadEndpoint()); } } } } } else { if (equals(conflict.getSourceResourceId(), conflictDocument.getResourceId())) { logger.info("DELETE conflict found @ {}", client.getReadEndpoint()); return false; } } } logger.error("Document {} is not found in conflict feed @ {}, retrying", conflictDocument.getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } private void deleteConflict(Document conflictDocument) { AsyncDocumentClient delClient = clients.get(0); FeedResponse<Conflict> conflicts = delClient.readConflicts(this.manualCollectionUri, null).take(1).single().block(); for (Conflict conflict : conflicts.getResults()) { if (!isDelete(conflict)) { Document conflictContent = conflict.getResource(Document.class); if (equals(conflictContent.getResourceId(), conflictDocument.getResourceId()) && equals(conflictContent.getETag(), conflictDocument.getETag())) { logger.info("Deleting manual conflict {} from region {}", conflict.getSourceResourceId(), conflictContent.getInt("regionId")); delClient.deleteConflict(conflict.getSelfLink(), null) .single().block(); } } else if (equals(conflict.getSourceResourceId(), conflictDocument.getResourceId())) { logger.info("Deleting manual conflict {} from region {}", conflict.getSourceResourceId(), conflictDocument.getInt("regionId")); delClient.deleteConflict(conflict.getSelfLink(), null) .single().block(); } } } private void validateLWW(List<AsyncDocumentClient> clients, List<Document> conflictDocument) throws Exception { validateLWW(clients, conflictDocument, false); } private void validateLWW(List<AsyncDocumentClient> clients, List<Document> conflictDocument, boolean hasDeleteConflict) throws Exception { for (AsyncDocumentClient client : clients) { this.validateLWW(client, conflictDocument, hasDeleteConflict); } } private void validateLWW(AsyncDocumentClient client, List<Document> conflictDocument, boolean hasDeleteConflict) throws Exception { FeedResponse<Conflict> response = client.readConflicts(this.lwwCollectionUri, null) .take(1).single().block(); if (response.getResults().size() != 0) { logger.error("Found {} conflicts in the lww collection", response.getResults().size()); return; } if (hasDeleteConflict) { do { try { client.readDocument(conflictDocument.get(0).getSelfLink(), null).single().block(); logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } catch (Exception exception) { if (!hasDocumentClientExceptionCause(exception)) { throw exception; } if (hasDocumentClientExceptionCause(exception, 404)) { logger.info("DELETE conflict won @ {}", client.getReadEndpoint()); return; } else { logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } } while (true); } Document winnerDocument = null; for (Document document : conflictDocument) { if (winnerDocument == null || winnerDocument.getInt("regionId") <= document.getInt("regionId")) { winnerDocument = document; } } logger.info("Document from region {} should be the winner", winnerDocument.getInt("regionId")); while (true) { try { Document existingDocument = client.readDocument(winnerDocument.getSelfLink(), null) .single().block().getResource(); if (existingDocument.getInt("regionId") == winnerDocument.getInt("regionId")) { logger.info("Winner document from region {} found at {}", existingDocument.getInt("regionId"), client.getReadEndpoint()); break; } else { logger.error("Winning document version from region {} is not found @ {}, retrying...", winnerDocument.getInt("regionId"), client.getWriteEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } catch (Exception e) { logger.error("Winner document from region {} is not found @ {}, retrying...", winnerDocument.getInt("regionId"), client.getWriteEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } } private void validateUDPAsync(List<AsyncDocumentClient> clients, List<Document> conflictDocument) throws Exception { validateUDPAsync(clients, conflictDocument, false); } private void validateUDPAsync(List<AsyncDocumentClient> clients, List<Document> conflictDocument, boolean hasDeleteConflict) throws Exception { for (AsyncDocumentClient client : clients) { this.validateUDPAsync(client, conflictDocument, hasDeleteConflict); } } private String documentNameLink(String collectionId, String documentId) { return String.format("dbs/%s/colls/%s/docs/%s", databaseName, collectionId, documentId); } private void validateUDPAsync(AsyncDocumentClient client, List<Document> conflictDocument, boolean hasDeleteConflict) throws Exception { FeedResponse<Conflict> response = client.readConflicts(this.udpCollectionUri, null).take(1).single().block(); if (response.getResults().size() != 0) { logger.error("Found {} conflicts in the udp collection", response.getResults().size()); return; } if (hasDeleteConflict) { do { try { client.readDocument( documentNameLink(udpCollectionName, conflictDocument.get(0).getId()), null) .single().block(); logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } catch (Exception exception) { if (hasDocumentClientExceptionCause(exception, 404)) { logger.info("DELETE conflict won @ {}", client.getReadEndpoint()); return; } else { logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } } while (true); } Document winnerDocument = null; for (Document document : conflictDocument) { if (winnerDocument == null || winnerDocument.getInt("regionId") <= document.getInt("regionId")) { winnerDocument = document; } } logger.info("Document from region {} should be the winner", winnerDocument.getInt("regionId")); while (true) { try { Document existingDocument = client.readDocument( documentNameLink(udpCollectionName, winnerDocument.getId()), null) .single().block().getResource(); if (existingDocument.getInt("regionId") == winnerDocument.getInt( ("regionId"))) { logger.info("Winner document from region {} found at {}", existingDocument.getInt("regionId"), client.getReadEndpoint()); break; } else { logger.error("Winning document version from region {} is not found @ {}, retrying...", winnerDocument.getInt("regionId"), client.getWriteEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } catch (Exception e) { logger.error("Winner document from region {} is not found @ {}, retrying...", winnerDocument.getInt("regionId"), client.getWriteEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } } public void shutdown() { this.executor.shutdown(); for(AsyncDocumentClient client: clients) { client.close(); } } }
class ConflictWorker { private static Logger logger = LoggerFactory.getLogger(ConflictWorker.class); private final Scheduler schedulerForBlockingWork; private final List<AsyncDocumentClient> clients; private final String basicCollectionUri; private final String manualCollectionUri; private final String lwwCollectionUri; private final String udpCollectionUri; private final String databaseName; private final String basicCollectionName; private final String manualCollectionName; private final String lwwCollectionName; private final String udpCollectionName; private final ExecutorService executor; public ConflictWorker(String databaseName, String basicCollectionName, String manualCollectionName, String lwwCollectionName, String udpCollectionName) { this.clients = new ArrayList<>(); this.basicCollectionUri = Helpers.createDocumentCollectionUri(databaseName, basicCollectionName); this.manualCollectionUri = Helpers.createDocumentCollectionUri(databaseName, manualCollectionName); this.lwwCollectionUri = Helpers.createDocumentCollectionUri(databaseName, lwwCollectionName); this.udpCollectionUri = Helpers.createDocumentCollectionUri(databaseName, udpCollectionName); this.databaseName = databaseName; this.basicCollectionName = basicCollectionName; this.manualCollectionName = manualCollectionName; this.lwwCollectionName = lwwCollectionName; this.udpCollectionName = udpCollectionName; this.executor = Executors.newFixedThreadPool(100); this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public void addClient(AsyncDocumentClient client) { this.clients.add(client); } private DocumentCollection createCollectionIfNotExists(AsyncDocumentClient createClient, String databaseName, DocumentCollection collection) { return Helpers.createCollectionIfNotExists(createClient, this.databaseName, collection) .subscribeOn(schedulerForBlockingWork).block(); } private DocumentCollection createCollectionIfNotExists(AsyncDocumentClient createClient, String databaseName, String collectionName) { return Helpers.createCollectionIfNotExists(createClient, this.databaseName, this.basicCollectionName) .subscribeOn(schedulerForBlockingWork).block(); } private DocumentCollection getCollectionDefForManual(String id) { DocumentCollection collection = new DocumentCollection(); collection.setId(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy(); collection.setConflictResolutionPolicy(policy); return collection; } private DocumentCollection getCollectionDefForLastWinWrites(String id, String conflictResolutionPath) { DocumentCollection collection = new DocumentCollection(); collection.setId(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createLastWriterWinsPolicy(conflictResolutionPath); collection.setConflictResolutionPolicy(policy); return collection; } private DocumentCollection getCollectionDefForCustom(String id, String storedProc) { DocumentCollection collection = new DocumentCollection(); collection.setId(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy(storedProc); collection.setConflictResolutionPolicy(policy); return collection; } public void initialize() throws Exception { AsyncDocumentClient createClient = this.clients.get(0); Helpers.createDatabaseIfNotExists(createClient, this.databaseName).subscribeOn(schedulerForBlockingWork).block(); DocumentCollection basic = createCollectionIfNotExists(createClient, this.databaseName, this.basicCollectionName); DocumentCollection manualCollection = createCollectionIfNotExists(createClient, Helpers.createDatabaseUri(this.databaseName), getCollectionDefForManual(this.manualCollectionName)); DocumentCollection lwwCollection = createCollectionIfNotExists(createClient, Helpers.createDatabaseUri(this.databaseName), getCollectionDefForLastWinWrites(this.lwwCollectionName, "/regionId")); DocumentCollection udpCollection = createCollectionIfNotExists(createClient, Helpers.createDatabaseUri(this.databaseName), getCollectionDefForCustom(this.udpCollectionName, String.format("dbs/%s/colls/%s/sprocs/%s", this.databaseName, this.udpCollectionName, "resolver"))); StoredProcedure lwwSproc = new StoredProcedure(); lwwSproc.setId("resolver"); lwwSproc.setBody(IOUtils.toString( getClass().getClassLoader().getResourceAsStream("resolver-storedproc.txt"), "UTF-8")); lwwSproc = getResource(createClient.upsertStoredProcedure( Helpers.createDocumentCollectionUri(this.databaseName, this.udpCollectionName), lwwSproc, null)); } private <T extends Resource> T getResource(Mono<ResourceResponse<T>> obs) { return obs.subscribeOn(schedulerForBlockingWork).single().block().getResource(); } public void runManualConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnManual(); logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnManual(); logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnManual(); } public void runLWWConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnLWW(); logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnLWW(); logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnLWW(); } public void runUDPConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnUdp(); logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnUdp(); logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnUdp(); } public void runInsertConflictOnManual() throws Exception { do { logger.info("1) Performing conflicting insert across {} regions on {}", this.clients.size(), this.manualCollectionName); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryInsertDocument(client, this.manualCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().subscribeOn(schedulerForBlockingWork).single().block(); if (conflictDocuments.size() == this.clients.size()) { logger.info("2) Caused {} insert conflicts, verifying conflict resolution", conflictDocuments.size()); for (Document conflictingInsert : conflictDocuments) { this.validateManualConflict(this.clients, conflictingInsert); } break; } else { logger.info("Retrying insert to induce conflicts"); } } while (true); } public void runUpdateConflictOnManual() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.manualCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting update across 3 regions on {}", this.manualCollectionName); ArrayList<Mono<Document>> updateTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { updateTask.add(this.tryUpdateDocument(client, this.manualCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(updateTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} updated conflicts, verifying conflict resolution", conflictDocuments.size()); for (Document conflictingUpdate : conflictDocuments) { this.validateManualConflict(this.clients, conflictingUpdate); } break; } else { logger.info("Retrying update to induce conflicts"); } } while (true); } public void runDeleteConflictOnManual() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.manualCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(10); logger.info("1) Performing conflicting delete across 3 regions on {}", this.manualCollectionName); ArrayList<Mono<Document>> deleteTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { deleteTask.add(this.tryDeleteDocument(client, this.manualCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(deleteTask).collectList() .subscribeOn(schedulerForBlockingWork) .single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} delete conflicts, verifying conflict resolution", conflictDocuments.size()); for (Document conflictingDelete : conflictDocuments) { this.validateManualConflict(this.clients, conflictingDelete); } break; } else { logger.info("Retrying update to induce conflicts"); } } while (true); } public void runInsertConflictOnLWW() throws Exception { do { logger.info("Performing conflicting insert across 3 regions"); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryInsertDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("Inserted {} conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateLWW(this.clients, conflictDocuments); break; } else { logger.info("Retrying insert to induce conflicts"); } } while (true); } public void runUpdateConflictOnLWW() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.lwwCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting update across {} regions on {}", this.clients.size(), this.lwwCollectionUri); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryUpdateDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} update conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateLWW(this.clients, conflictDocuments); break; } else { logger.info("Retrying insert to induce conflicts"); } } while (true); } public void runDeleteConflictOnLWW() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.lwwCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting delete across {} regions on {}", this.clients.size(), this.lwwCollectionUri); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { if (index % 2 == 1) { insertTask.add(this.tryDeleteDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } else { insertTask.add(this.tryUpdateDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("Inserted {} conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateLWW(this.clients, conflictDocuments, true); break; } else { logger.info("Retrying update/delete to induce conflicts"); } } while (true); } public void runInsertConflictOnUdp() throws Exception { do { logger.info("1) Performing conflicting insert across 3 regions on {}", this.udpCollectionName); ArrayList<Mono<Document>> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryInsertDocument(client, this.udpCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} insert conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateUDPAsync(this.clients, conflictDocuments); break; } else { logger.info("Retrying insert to induce conflicts"); } } while (true); } public void runUpdateConflictOnUdp() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.udpCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting update across 3 regions on {}", this.udpCollectionUri); ArrayList<Mono<Document>> updateTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { updateTask.add(this.tryUpdateDocument(client, this.udpCollectionUri, conflictDocument, index++)); } List<Document> conflictDocuments = Flux.merge(updateTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} update conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateUDPAsync(this.clients, conflictDocuments); break; } else { logger.info("Retrying update to induce conflicts"); } } while (true); } public void runDeleteConflictOnUdp() throws Exception { do { Document conflictDocument = new Document(); conflictDocument.setId(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.udpCollectionUri, conflictDocument, 0) .block(); TimeUnit.SECONDS.sleep(1); logger.info("1) Performing conflicting update/delete across 3 regions on {}", this.udpCollectionUri); ArrayList<Mono<Document>> deleteTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { if (index % 2 == 1) { deleteTask.add(this.tryDeleteDocument(client, this.udpCollectionUri, conflictDocument, index++)); } else { deleteTask.add(this.tryUpdateDocument(client, this.udpCollectionUri, conflictDocument, index++)); } } List<Document> conflictDocuments = Flux.merge(deleteTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} delete conflicts, verifying conflict resolution", conflictDocuments.size()); this.validateUDPAsync(this.clients, conflictDocuments, true); break; } else { logger.info("Retrying update/delete to induce conflicts"); } } while (true); } private Mono<Document> tryInsertDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { logger.debug("region: {}", client.getWriteEndpoint()); BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); return client.createDocument(collectionUri, document, null, false) .onErrorResume(e -> { if (hasDocumentClientException(e, 409)) { return Mono.empty(); } else { return Mono.error(e); } }).map(ResourceResponse::getResource); } private boolean hasDocumentClientException(Throwable e, int statusCode) { if (e instanceof CosmosException) { CosmosException dce = (CosmosException) e; return dce.getStatusCode() == statusCode; } return false; } private boolean hasDocumentClientExceptionCause(Throwable e) { while (e != null) { if (e instanceof CosmosException) { return true; } e = e.getCause(); } return false; } private boolean hasDocumentClientExceptionCause(Throwable e, int statusCode) { while (e != null) { if (e instanceof CosmosException) { CosmosException dce = (CosmosException) e; return dce.getStatusCode() == statusCode; } e = e.getCause(); } return false; } private Mono<Document> tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setIfMatchETag(document.getETag()); return client.replaceDocument(document.getSelfLink(), document, null).onErrorResume(e -> { if (hasDocumentClientException(e, 412)) { return Mono.empty(); } return Mono.error(e); }).map(ResourceResponse::getResource); } private Mono<Document> tryDeleteDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { BridgeInternal.setProperty(document, "regionId", index); BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setIfMatchETag(document.getETag()); return client.deleteDocument(document.getSelfLink(), options).onErrorResume(e -> { if (hasDocumentClientException(e, 412)) { return Mono.empty(); } return Mono.error(e); }).map(rr -> document); } private void validateManualConflict(List<AsyncDocumentClient> clients, Document conflictDocument) throws Exception { boolean conflictExists = false; for (AsyncDocumentClient client : clients) { conflictExists = this.validateManualConflict(client, conflictDocument); } if (conflictExists) { this.deleteConflict(conflictDocument); } } private boolean equals(String a, String b) { return StringUtils.equals(a, b); } private boolean validateManualConflict(AsyncDocumentClient client, Document conflictDocument) throws Exception { while (true) { FeedResponse<Conflict> response = client.readConflicts(this.manualCollectionUri, null) .take(1).single().block(); for (Conflict conflict : response.getResults()) { if (!isDelete(conflict)) { Document conflictDocumentContent = conflict.getResource(Document.class); if (equals(conflictDocument.getId(), conflictDocumentContent.getId())) { if (equals(conflictDocument.getResourceId(), conflictDocumentContent.getResourceId()) && equals(conflictDocument.getETag(), conflictDocumentContent.getETag())) { logger.info("Document from Region {} lost conflict @ {}", conflictDocument.getId(), conflictDocument.getInt("regionId"), client.getReadEndpoint()); return true; } else { try { Document winnerDocument = client.readDocument(conflictDocument.getSelfLink(), null) .single().block().getResource(); logger.info("Document from region {} won the conflict @ {}", conflictDocument.getInt("regionId"), client.getReadEndpoint()); return false; } catch (Exception exception) { if (hasDocumentClientException(exception, 404)) { throw exception; } else { logger.info( "Document from region {} not found @ {}", conflictDocument.getInt("regionId"), client.getReadEndpoint()); } } } } } else { if (equals(conflict.getSourceResourceId(), conflictDocument.getResourceId())) { logger.info("DELETE conflict found @ {}", client.getReadEndpoint()); return false; } } } logger.error("Document {} is not found in conflict feed @ {}, retrying", conflictDocument.getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } private void deleteConflict(Document conflictDocument) { AsyncDocumentClient delClient = clients.get(0); FeedResponse<Conflict> conflicts = delClient.readConflicts(this.manualCollectionUri, null).take(1).single().block(); for (Conflict conflict : conflicts.getResults()) { if (!isDelete(conflict)) { Document conflictContent = conflict.getResource(Document.class); if (equals(conflictContent.getResourceId(), conflictDocument.getResourceId()) && equals(conflictContent.getETag(), conflictDocument.getETag())) { logger.info("Deleting manual conflict {} from region {}", conflict.getSourceResourceId(), conflictContent.getInt("regionId")); delClient.deleteConflict(conflict.getSelfLink(), null) .single().block(); } } else if (equals(conflict.getSourceResourceId(), conflictDocument.getResourceId())) { logger.info("Deleting manual conflict {} from region {}", conflict.getSourceResourceId(), conflictDocument.getInt("regionId")); delClient.deleteConflict(conflict.getSelfLink(), null) .single().block(); } } } private void validateLWW(List<AsyncDocumentClient> clients, List<Document> conflictDocument) throws Exception { validateLWW(clients, conflictDocument, false); } private void validateLWW(List<AsyncDocumentClient> clients, List<Document> conflictDocument, boolean hasDeleteConflict) throws Exception { for (AsyncDocumentClient client : clients) { this.validateLWW(client, conflictDocument, hasDeleteConflict); } } private void validateLWW(AsyncDocumentClient client, List<Document> conflictDocument, boolean hasDeleteConflict) throws Exception { FeedResponse<Conflict> response = client.readConflicts(this.lwwCollectionUri, null) .take(1).single().block(); if (response.getResults().size() != 0) { logger.error("Found {} conflicts in the lww collection", response.getResults().size()); return; } if (hasDeleteConflict) { do { try { client.readDocument(conflictDocument.get(0).getSelfLink(), null).single().block(); logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } catch (Exception exception) { if (!hasDocumentClientExceptionCause(exception)) { throw exception; } if (hasDocumentClientExceptionCause(exception, 404)) { logger.info("DELETE conflict won @ {}", client.getReadEndpoint()); return; } else { logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } } while (true); } Document winnerDocument = null; for (Document document : conflictDocument) { if (winnerDocument == null || winnerDocument.getInt("regionId") <= document.getInt("regionId")) { winnerDocument = document; } } logger.info("Document from region {} should be the winner", winnerDocument.getInt("regionId")); while (true) { try { Document existingDocument = client.readDocument(winnerDocument.getSelfLink(), null) .single().block().getResource(); if (existingDocument.getInt("regionId") == winnerDocument.getInt("regionId")) { logger.info("Winner document from region {} found at {}", existingDocument.getInt("regionId"), client.getReadEndpoint()); break; } else { logger.error("Winning document version from region {} is not found @ {}, retrying...", winnerDocument.getInt("regionId"), client.getWriteEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } catch (Exception e) { logger.error("Winner document from region {} is not found @ {}, retrying...", winnerDocument.getInt("regionId"), client.getWriteEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } } private void validateUDPAsync(List<AsyncDocumentClient> clients, List<Document> conflictDocument) throws Exception { validateUDPAsync(clients, conflictDocument, false); } private void validateUDPAsync(List<AsyncDocumentClient> clients, List<Document> conflictDocument, boolean hasDeleteConflict) throws Exception { for (AsyncDocumentClient client : clients) { this.validateUDPAsync(client, conflictDocument, hasDeleteConflict); } } private String documentNameLink(String collectionId, String documentId) { return String.format("dbs/%s/colls/%s/docs/%s", databaseName, collectionId, documentId); } private void validateUDPAsync(AsyncDocumentClient client, List<Document> conflictDocument, boolean hasDeleteConflict) throws Exception { FeedResponse<Conflict> response = client.readConflicts(this.udpCollectionUri, null).take(1).single().block(); if (response.getResults().size() != 0) { logger.error("Found {} conflicts in the udp collection", response.getResults().size()); return; } if (hasDeleteConflict) { do { try { client.readDocument( documentNameLink(udpCollectionName, conflictDocument.get(0).getId()), null) .single().block(); logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } catch (Exception exception) { if (hasDocumentClientExceptionCause(exception, 404)) { logger.info("DELETE conflict won @ {}", client.getReadEndpoint()); return; } else { logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).getId(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } } while (true); } Document winnerDocument = null; for (Document document : conflictDocument) { if (winnerDocument == null || winnerDocument.getInt("regionId") <= document.getInt("regionId")) { winnerDocument = document; } } logger.info("Document from region {} should be the winner", winnerDocument.getInt("regionId")); while (true) { try { Document existingDocument = client.readDocument( documentNameLink(udpCollectionName, winnerDocument.getId()), null) .single().block().getResource(); if (existingDocument.getInt("regionId") == winnerDocument.getInt( ("regionId"))) { logger.info("Winner document from region {} found at {}", existingDocument.getInt("regionId"), client.getReadEndpoint()); break; } else { logger.error("Winning document version from region {} is not found @ {}, retrying...", winnerDocument.getInt("regionId"), client.getWriteEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } catch (Exception e) { logger.error("Winner document from region {} is not found @ {}, retrying...", winnerDocument.getInt("regionId"), client.getWriteEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } } } public void shutdown() { this.executor.shutdown(); for(AsyncDocumentClient client: clients) { client.close(); } } }
can we have more `/` in the path ? if yes then should we encode them?
public static String encodeUrlPath(String url) { /* Deconstruct the URL and reconstruct it making sure the path is encoded. */ UrlBuilder builder = UrlBuilder.parse(url); String path = builder.getPath(); if (path.startsWith("/")) { path = path.substring(1); } path = Utility.urlEncode(Utility.urlDecode(path)); builder.setPath(path); return builder.toString(); }
if (path.startsWith("/")) {
public static String encodeUrlPath(String url) { /* Deconstruct the URL and reconstruct it making sure the path is encoded. */ UrlBuilder builder = UrlBuilder.parse(url); String path = builder.getPath(); if (path.startsWith("/")) { path = path.substring(1); } path = Utility.urlEncode(Utility.urlDecode(path)); builder.setPath(path); return builder.toString(); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String UTF8_CHARSET = "UTF-8"; private static final String INVALID_DATE_STRING = "Invalid Date String: %s."; public static final String STORAGE_TRACING_NAMESPACE_VALUE = "Microsoft.Storage"; /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "") .length(); /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (CoreUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return ""; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of a url string, only encoding the path. * * @param url The url to encode. * @return The encoded url. */ /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int numOfBytes = 0; int offset = 0; int len = (int) count; while (numOfBytes != -1 && offset < count) { numOfBytes = data.read(cache, offset, len); offset += numOfBytes; len -= numOfBytes; if (numOfBytes != -1) { currentTotalLength[0] += numOfBytes; } } if (numOfBytes == -1 && currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error details: " + e.getMessage())); } }); } }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String UTF8_CHARSET = "UTF-8"; private static final String INVALID_DATE_STRING = "Invalid Date String: %s."; public static final String STORAGE_TRACING_NAMESPACE_VALUE = "Microsoft.Storage"; /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "") .length(); /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (CoreUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return ""; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of a url string, only encoding the path. * * @param url The url to encode. * @return The encoded url. */ /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int numOfBytes = 0; int offset = 0; int len = (int) count; while (numOfBytes != -1 && offset < count) { numOfBytes = data.read(cache, offset, len); offset += numOfBytes; len -= numOfBytes; if (numOfBytes != -1) { currentTotalLength[0] += numOfBytes; } } if (numOfBytes == -1 && currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error details: " + e.getMessage())); } }); } }
do we have to decode it first ? Wouldn't already encoded chars be left alone during encoding?
public static String encodeUrlPath(String url) { /* Deconstruct the URL and reconstruct it making sure the path is encoded. */ UrlBuilder builder = UrlBuilder.parse(url); String path = builder.getPath(); if (path.startsWith("/")) { path = path.substring(1); } path = Utility.urlEncode(Utility.urlDecode(path)); builder.setPath(path); return builder.toString(); }
path = Utility.urlEncode(Utility.urlDecode(path));
public static String encodeUrlPath(String url) { /* Deconstruct the URL and reconstruct it making sure the path is encoded. */ UrlBuilder builder = UrlBuilder.parse(url); String path = builder.getPath(); if (path.startsWith("/")) { path = path.substring(1); } path = Utility.urlEncode(Utility.urlDecode(path)); builder.setPath(path); return builder.toString(); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String UTF8_CHARSET = "UTF-8"; private static final String INVALID_DATE_STRING = "Invalid Date String: %s."; public static final String STORAGE_TRACING_NAMESPACE_VALUE = "Microsoft.Storage"; /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "") .length(); /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (CoreUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return ""; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of a url string, only encoding the path. * * @param url The url to encode. * @return The encoded url. */ /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int numOfBytes = 0; int offset = 0; int len = (int) count; while (numOfBytes != -1 && offset < count) { numOfBytes = data.read(cache, offset, len); offset += numOfBytes; len -= numOfBytes; if (numOfBytes != -1) { currentTotalLength[0] += numOfBytes; } } if (numOfBytes == -1 && currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error details: " + e.getMessage())); } }); } }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String UTF8_CHARSET = "UTF-8"; private static final String INVALID_DATE_STRING = "Invalid Date String: %s."; public static final String STORAGE_TRACING_NAMESPACE_VALUE = "Microsoft.Storage"; /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "") .length(); /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (CoreUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return ""; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of a url string, only encoding the path. * * @param url The url to encode. * @return The encoded url. */ /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int numOfBytes = 0; int offset = 0; int len = (int) count; while (numOfBytes != -1 && offset < count) { numOfBytes = data.read(cache, offset, len); offset += numOfBytes; len -= numOfBytes; if (numOfBytes != -1) { currentTotalLength[0] += numOfBytes; } } if (numOfBytes == -1 && currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error details: " + e.getMessage())); } }); } }