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
Should we test it for both 307 and 308 as both are our default redirect strategy return codes?
public void defaultRedirectAuthorizationHeaderCleared() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: headers.put("Authorization", "12345"); HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy()) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(200, response.getStatusCode()); assertNull(response.getHeaders().getValue("Authorization")); }
return Mono.just(new MockHttpResponse(request, 308, httpHeader));
public void defaultRedirectAuthorizationHeaderCleared() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: headers.put("Authorization", "12345"); HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy()) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(200, response.getStatusCode()); assertNull(response.getHeaders().getValue("Authorization")); }
class RedirectPolicyTest { @Test public void noRedirectPolicyTest() throws Exception { final HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(new NoOpHttpClient() { @Override public Mono<HttpResponse> send(HttpRequest request) { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } } }) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(308, response.getStatusCode()); } @Test public void defaultRedirectWhen308() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy()) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(200, response.getStatusCode()); } @Test public void redirectForNAttempts() throws MalformedURLException { final int[] requestCount = {1}; RecordingHttpClient httpClient = new RecordingHttpClient(request -> { Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); requestCount[0]++; return Mono.just(new MockHttpResponse(request, 308, httpHeader)); }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy(5))) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(5, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectNonAllowedMethodTest() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy(5))) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.POST, new URL("http: assertEquals(1, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectAllowedStatusCodesTest() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy())) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(2, httpClient.getCount()); assertEquals(200, response.getStatusCode()); } @Test public void alreadyAttemptedUrlsTest() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy())) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(2, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectForProvidedHeader() throws MalformedURLException { final int[] requestCount = {1}; RecordingHttpClient httpClient = new RecordingHttpClient(request -> { Map<String, String> headers = new HashMap<>(); headers.put("Location1", "http: HttpHeaders httpHeader = new HttpHeaders(headers); requestCount[0]++; return Mono.just(new MockHttpResponse(request, 308, httpHeader)); }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy(5, "Location1", null))) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(5, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectForProvidedMethods() throws MalformedURLException { Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>() { { add(HttpMethod.GET); add(HttpMethod.PUT); add(HttpMethod.POST); } }; final int[] requestCount = {1}; RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); request.setHttpMethod(HttpMethod.PUT); requestCount[0]++; return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else if (request.getUrl().toString().equals("http: && requestCount[0] == 2) { Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); request.setHttpMethod(HttpMethod.POST); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy(5, null, allowedMethods))) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(2, httpClient.getCount()); assertEquals(200, response.getStatusCode()); } @Test public void nullRedirectUrlTest() throws MalformedURLException { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy())) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(1, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectForMultipleRequests() throws MalformedURLException { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy()) .build(); HttpResponse response1 = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: HttpResponse response2 = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(4, httpClient.getCount()); assertEquals(200, response1.getStatusCode()); assertEquals(200, response2.getStatusCode()); } @Test public void nonRedirectRequest() throws MalformedURLException { final HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(new NoOpHttpClient() { @Override public Mono<HttpResponse> send(HttpRequest request) { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 401, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } } }) .policies(new RedirectPolicy()) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(401, response.getStatusCode()); } @Test static class RecordingHttpClient implements HttpClient { private final AtomicInteger count = new AtomicInteger(); private final Function<HttpRequest, Mono<HttpResponse>> handler; RecordingHttpClient(Function<HttpRequest, Mono<HttpResponse>> handler) { this.handler = handler; } @Override public Mono<HttpResponse> send(HttpRequest httpRequest) { count.getAndIncrement(); return handler.apply(httpRequest); } int getCount() { return count.get(); } void resetCount() { count.set(0); } } }
class RedirectPolicyTest { @Test public void noRedirectPolicyTest() throws Exception { final HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(new NoOpHttpClient() { @Override public Mono<HttpResponse> send(HttpRequest request) { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } } }) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(308, response.getStatusCode()); } @ParameterizedTest @ValueSource(ints = {308, 307, 301, 302}) public void defaultRedirectExpectedStatusCodes(int statusCode) throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: headers.put("Authorization", "12345"); HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, statusCode, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy()) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(200, response.getStatusCode()); assertNull(response.getHeaders().getValue("Authorization")); } @Test public void redirectForNAttempts() throws MalformedURLException { final int[] requestCount = {1}; RecordingHttpClient httpClient = new RecordingHttpClient(request -> { Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); requestCount[0]++; return Mono.just(new MockHttpResponse(request, 308, httpHeader)); }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy(5))) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(5, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectNonAllowedMethodTest() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy(5))) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.POST, new URL("http: assertEquals(1, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectAllowedStatusCodesTest() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy())) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(2, httpClient.getCount()); assertEquals(200, response.getStatusCode()); } @Test public void alreadyAttemptedUrlsTest() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy())) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(2, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectForProvidedHeader() throws MalformedURLException { final int[] requestCount = {1}; RecordingHttpClient httpClient = new RecordingHttpClient(request -> { Map<String, String> headers = new HashMap<>(); headers.put("Location1", "http: HttpHeaders httpHeader = new HttpHeaders(headers); requestCount[0]++; return Mono.just(new MockHttpResponse(request, 308, httpHeader)); }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy(5, "Location1", null))) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(5, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectForProvidedMethods() throws MalformedURLException { Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>() { { add(HttpMethod.GET); add(HttpMethod.PUT); add(HttpMethod.POST); } }; final int[] requestCount = {1}; RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); request.setHttpMethod(HttpMethod.PUT); requestCount[0]++; return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else if (request.getUrl().toString().equals("http: && requestCount[0] == 2) { Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); request.setHttpMethod(HttpMethod.POST); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy(5, null, allowedMethods))) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(2, httpClient.getCount()); assertEquals(200, response.getStatusCode()); } @Test public void nullRedirectUrlTest() throws MalformedURLException { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy(new DefaultRedirectStrategy())) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(1, httpClient.getCount()); assertEquals(308, response.getStatusCode()); } @Test public void redirectForMultipleRequests() throws MalformedURLException { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); headers.put("Location", "http: HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 308, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } }); HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(httpClient) .policies(new RedirectPolicy()) .build(); HttpResponse response1 = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: HttpResponse response2 = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(4, httpClient.getCount()); assertEquals(200, response1.getStatusCode()); assertEquals(200, response2.getStatusCode()); } @Test public void nonRedirectRequest() throws MalformedURLException { final HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(new NoOpHttpClient() { @Override public Mono<HttpResponse> send(HttpRequest request) { if (request.getUrl().toString().equals("http: Map<String, String> headers = new HashMap<>(); HttpHeaders httpHeader = new HttpHeaders(headers); return Mono.just(new MockHttpResponse(request, 401, httpHeader)); } else { return Mono.just(new MockHttpResponse(request, 200)); } } }) .policies(new RedirectPolicy()) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http: assertEquals(401, response.getStatusCode()); } @Test static class RecordingHttpClient implements HttpClient { private final AtomicInteger count = new AtomicInteger(); private final Function<HttpRequest, Mono<HttpResponse>> handler; RecordingHttpClient(Function<HttpRequest, Mono<HttpResponse>> handler) { this.handler = handler; } @Override public Mono<HttpResponse> send(HttpRequest httpRequest) { count.getAndIncrement(); return handler.apply(httpRequest); } int getCount() { return count.get(); } void resetCount() { count.set(0); } } }
It's possible people hold onto the same builder and build multiple clients from it. Initialising it here will always have the same identifier.
public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; identifier = UUID.randomUUID().toString(); }
identifier = UUID.randomUUID().toString();
public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder>, IdentifierTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; private String identifier; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * {@inheritDoc} */ @Override public EventHubClientBuilder identifier(String identifier) { this.identifier = Objects.requireNonNull(identifier, "'identifier' cannot be null."); return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw logger.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, this.identifier); } /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { logger.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(logger.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); logger.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { logger.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); } /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
We should allow setting `null` if the user wants to clear the previously set identifier.
public AmqpClientOptions setIdentifier(String identifier) { this.identifier = Objects.requireNonNull(identifier, "'identifier' cannot be null."); return this; }
this.identifier = Objects.requireNonNull(identifier, "'identifier' cannot be null.");
public AmqpClientOptions setIdentifier(String identifier) { this.identifier = identifier; return this; }
class AmqpClientOptions extends ClientOptions { private String identifier = UUID.randomUUID().toString(); /** {@inheritDoc} **/ @Override public ClientOptions setApplicationId(String applicationId) { super.setApplicationId(applicationId); return this; } /** {@inheritDoc} **/ @Override public ClientOptions setHeaders(Iterable<Header> headers) { super.setHeaders(headers); return this; } /** * Gets the identifier for the amqp client. * @return Amqp client identifier. */ public String getIdentifier() { return identifier; } /** * Sets the identifier for the amqp client. * @param identifier a specific string to identify amqp client. * @return The updated {@link AmqpRetryOptions} object. */ }
class AmqpClientOptions extends ClientOptions { private String identifier; /** {@inheritDoc} **/ @Override public AmqpClientOptions setApplicationId(String applicationId) { super.setApplicationId(applicationId); return this; } /** {@inheritDoc} **/ @Override public AmqpClientOptions setHeaders(Iterable<Header> headers) { super.setHeaders(headers); return this; } /** * Gets the identifier for the AMQP client. * @return AMQP client identifier. */ public String getIdentifier() { return identifier; } /** * Sets the identifier for the AMQP client. * @param identifier A specific string to identify AMQP client. If null or empty, a UUID will be used as the * identifier. * @return The updated {@link AmqpClientOptions} object. */ }
Are we not doing this in `EventProcessorClientBuilder`?
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
the `binaryData.getLength()` may return `null` which means it didn't measure length eagerly. If this happens we should get the `BinaryDataContent` from inside and decorate it depending on type. I.e. if it's `FluxByteBufferContent` then fall back to the old `validateLength` or maybe just throw exception and don't accept Flux at all (I think this might be better). If it's `InputStreamContent` then decorate stream with `LengthValidatingInputStream`.
static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); long length = binaryData.getLength(); if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, binaryData.getLength(), expectedLength), binaryData.getLength(), expectedLength); } return binaryData; }
long length = binaryData.getLength();
static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } }
class is if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); }
class is if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); }
We pass a `EventHubClientBuilder` to `EventProcessorClientBuilder`, user set `AmqpClientOptions` to `EventProcessorClientBuilder` will set to the `EventHubClientBuilder`, so processor client and the asyncClient in partition pumper will use the same identifier if user set a specific in `AmqpClientOptions`. Is it OK to do like this?
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
@jsquire may know... Do we allow users to set a client identifier for EventProcessorClient? (ie. does that mean all the new underlying AMQP connections it creates, also use that identifier?)
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
We do, and yes. For the processor, this is especially important as we recommend users set a stable identifier for each processor instance. Doing so allows the processor to enter recovery mode if the host crashes and reboots, since the partitions that it previously owned are associated with the identifier. Rather than going though load balancing and stealing random partitions because the old identifier still owns partitions until all of its ownership records expire, the rebooted processor can see that **it** should own those partitions, and the other processors in the group recognize this as well. This prevents ownership from bouncing around, rewinds and duplication is reduced, and the rebooted instance can get back up to full speed quickly.
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
nit, I think `instanceof` includes null check. Do we have validation on the string? What happens if I put string of 20MB? What's in other language SDK? If we do validate, should we validate in `AmqpClientOptions`? Also we default to UUID if not provided. Should we default that to `AmqpClientOptions`? So that user can call `AmqpClientOptions.getIdentifer()` to get this default value.
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
@jsquire Weidong has some new questions. We've talked about that we have no limit about identifier. But I have no idea about the behavior of `AmqpCLientOptions`. There are some detail I didn't think about it. Could you please help me answer these questions?
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
The question on validation is cross-language. If all SDK does not do validation, Java probably can skip that as well. I just want to know what happens if I (or user) put something unreasonable. Does it crash the client? Or just make the connection unusable? I just want something predictable. The later question on `AmqpClientOptions` is probably Java only. It might not be very important, as user can still call `client.getIdentifier` to get the value. (and this could be NOOP, if there is 1 to many from `AmqpClientOptions` to client, and client having different default identifier)
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
> Do we have validation on the string? What happens if I put string of 20MB? We intentionally do not validate on the client side. As a general rule, we try to avoid applying validation on the client and, instead, delegate to the service. This allows us to avoid the potential for disallowing values in the client that are valid to the service. > What's in other language SDK? Only that if the identifier is `null` or a zero-length string, it is set to a default value. > Should we default that to AmqpClientOptions? So that user can call AmqpClientOptions.getIdentifer() to get this default value This one comes down to a language idiom and should follow established Java patterns. @conniey or @srnagar would be better able to advise here.
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
Agree. But I still expect developer of the PR aka @ZejiaJiang know: 1. what is valid, what is not valid, from client or service 2. what would Java client behave if invalid identifier is provided (this is the simplest negative case in this PR) with the knowledge we may decide whether to add to documentation.
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
we should probably add generic `catch (Exception)` and `finally` to `try` block and make sure to close the tracing span.
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLength(request)); } final HttpResponse response = send(request, context); HttpDecodedResponse decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } }
context = startTracingSpan(method, context);
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); final SwaggerMethodParser methodParser = getMethodParser(method); HttpRequest request; try { request = createHttpRequest(methodParser, args); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); HttpDecodedResponse decodedResponse = null; Throwable throwable = null; try { context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLengthSync(request)); } final HttpResponse response = send(request, context); decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (Exception e) { throwable = e; if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } finally { if (decodedResponse != null || throwable != null) { endTracingSpan(decodedResponse, throwable, context); } } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSynchronously(request, contextData); } @Override @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); long length = binaryData.getLength(); if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, binaryData.getLength(), expectedLength), binaryData.getLength(), expectedLength); } return binaryData; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setContent(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setContent(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsByteArray().block(); if (responseBytes == null || responseBytes.length == 0) { throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().getBody().ignoreElements().block(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw new RuntimeException("Cannot find suitable constructor for class " + cls); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getContent().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getContent(); } else { result = response.getDecodedBody((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSync(request, contextData); } @Override @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } Exception e; byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsBinaryData().toBytes(); if (responseBytes == null || responseBytes.length == 0) { e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody); } if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().close(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getBodyAsBinaryData().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getBodyAsBinaryData(); } else { result = response.getDecodedBodySync((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(HttpDecodedResponse httpDecodedResponse, Throwable throwable, Context tracingContext) { if (tracingContext == null) { return; } Object disableTracingValue = (tracingContext.getData(Tracer.DISABLE_TRACING_KEY).isPresent() ? tracingContext.getData(Tracer.DISABLE_TRACING_KEY).get() : null); boolean disableTracing = Boolean.TRUE.equals(disableTracingValue != null ? disableTracingValue : false); if (disableTracing) { return; } int statusCode = 0; if (httpDecodedResponse != null) { statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (throwable != null) { if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
I did a small test. if we set a 20KB string as identifier, the client will crash, but 2 KB works. It cause a BufferOverflowException, the link created and reactor start processing. when client call `send()` method, the `getLinkSize()` return 0 and message encode failed, client crash.
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions != null && clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = clientOptionIdentifier == null ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
}
EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.boundedElastic(); } if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT; } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); LOGGER.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); String identifier; if (clientOptions instanceof AmqpClientOptions) { String clientOptionIdentifier = ((AmqpClientOptions) clientOptions).getIdentifier(); identifier = CoreUtils.isNullOrEmpty(clientOptionIdentifier) ? UUID.randomUUID().toString() : clientOptionIdentifier; } else { identifier = UUID.randomUUID().toString(); } return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose, identifier); }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
class EventHubClientBuilder implements TokenCredentialTrait<EventHubClientBuilder>, AzureNamedKeyCredentialTrait<EventHubClientBuilder>, ConnectionStringTrait<EventHubClientBuilder>, AzureSasCredentialTrait<EventHubClientBuilder>, AmqpTrait<EventHubClientBuilder>, ConfigurationTrait<EventHubClientBuilder> { static final int DEFAULT_PREFETCH_COUNT = 500; static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private static final ClientLogger LOGGER = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private Integer prefetchCount; private ClientOptions clientOptions; private SslDomain.VerifyMode verifyMode; private URL customEndpointAddress; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ @Override public EventHubClientBuilder connectionString(String connectionString) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } private TokenCredential getTokenCredential(ConnectionStringProperties properties) { TokenCredential tokenCredential; if (properties.getSharedAccessSignature() == null) { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); } else { tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); } return tokenCredential; } /** * Sets the client options. * * @param clientOptions The client options. * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); TokenCredential tokenCredential = getTokenCredential(properties); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network * does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through * an intermediary. For example: {@literal https: * <p> * If no port is specified, the default port for the {@link * used. * * @param customEndpointAddress The custom endpoint address. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}. */ public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) { if (customEndpointAddress == null) { this.customEndpointAddress = null; return this; } try { this.customEndpointAddress = new URL(customEndpointAddress); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e)); } return this; } /** * Sets the fully qualified name for the Event Hubs namespace. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} is an empty string. * @throws NullPointerException if {@code fullyQualifiedNamespace} is null. */ public EventHubClientBuilder fullyQualifiedNamespace(String fullyQualifiedNamespace) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } private String getAndValidateFullyQualifiedNamespace() { if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return fullyQualifiedNamespace; } /** * Sets the name of the Event Hub to connect the client to. * * @param eventHubName The name of the Event Hub to connect the client to. * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code eventHubName} is an empty string. * @throws NullPointerException if {@code eventHubName} is null. */ public EventHubClientBuilder eventHubName(String eventHubName) { this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } private String getEventHubName() { if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return eventHubName; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(TokenCredential credential) { this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureNamedKeyCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access name and key credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getAzureNamedKey().getName(), credential.getAzureNamedKey().getKey(), ClientConstants.TOKEN_VALIDITY); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, AzureSasCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param credential The shared access signature credential to use for authorization. * Access controls may be specified by the Event Hubs namespace or the requested Event Hub, * depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code credentials} is null. */ @Override public EventHubClientBuilder credential(AzureSasCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credentials = new EventHubSharedKeyCredential(credential.getSignature()); return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. * @deprecated Replaced by {@link */ @Deprecated public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ @Override public EventHubClientBuilder retryOptions(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that gets the prefetch count. * * @return Gets the prefetch count or {@code null} if it has not been set. * @see */ Integer getPrefetchCount() { return prefetchCount; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Package-private method that sets the verify mode for this connection. * * @param verifyMode The verification mode. * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) { this.verifyMode = verifyMode; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { if (prefetchCount == null) { prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT; } final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); LOGGER.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { LOGGER.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } LOGGER.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { LOGGER.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); LOGGER.atInfo() .addKeyValue(CONNECTION_ID_KEY, connectionId) .log("Emitting a single connection."); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, getEventHubName(), provider, handlerProvider, tokenManagerProvider, messageSerializer); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), getEventHubName(), connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = buildConfiguration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(buildConfiguration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; final SslDomain.VerifyMode verificationMode = verifyMode != null ? verifyMode : SslDomain.VerifyMode.VERIFY_PEER_NAME; final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions(); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); if (customEndpointAddress == null) { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion); } else { return new ConnectionOptions(getAndValidateFullyQualifiedNamespace(), credentials, authorizationType, ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE, transport, retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion, customEndpointAddress.getHost(), customEndpointAddress.getPort()); } } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress, configuration, Boolean.parseBoolean(configuration.get("java.net.useSystemProxies"))); } private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress, Configuration configuration, boolean useSystemProxies) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else if (useSystemProxies) { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); Proxy.Type proxyType = coreProxyOptions.getType().toProxyType(); InetSocketAddress coreProxyAddress = coreProxyOptions.getAddress(); String username = coreProxyOptions.getUsername(); String password = coreProxyOptions.getPassword(); return new ProxyOptions(authentication, new Proxy(proxyType, coreProxyAddress), username, password); } else { LOGGER.verbose("'HTTP_PROXY' was configured but ignored as 'java.net.useSystemProxies' wasn't " + "set or was false."); return ProxyOptions.SYSTEM_DEFAULTS; } } }
let's not use `Exceptions.propagate` in any of sync call stacks. This is going to throw exception from reactor. `UncheckedIOException` is better candidate here.
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLength(request)); } final HttpResponse response = send(request, context); HttpDecodedResponse decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } }
throw LOGGER.logExceptionAsError(Exceptions.propagate(e));
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); final SwaggerMethodParser methodParser = getMethodParser(method); HttpRequest request; try { request = createHttpRequest(methodParser, args); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); HttpDecodedResponse decodedResponse = null; Throwable throwable = null; try { context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLengthSync(request)); } final HttpResponse response = send(request, context); decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (Exception e) { throwable = e; if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } finally { if (decodedResponse != null || throwable != null) { endTracingSpan(decodedResponse, throwable, context); } } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSynchronously(request, contextData); } @Override @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); long length = binaryData.getLength(); if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, binaryData.getLength(), expectedLength), binaryData.getLength(), expectedLength); } return binaryData; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setContent(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setContent(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsByteArray().block(); if (responseBytes == null || responseBytes.length == 0) { throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().getBody().ignoreElements().block(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw new RuntimeException("Cannot find suitable constructor for class " + cls); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getContent().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getContent(); } else { result = response.getDecodedBody((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSync(request, contextData); } @Override @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } Exception e; byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsBinaryData().toBytes(); if (responseBytes == null || responseBytes.length == 0) { e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody); } if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().close(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getBodyAsBinaryData().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getBodyAsBinaryData(); } else { result = response.getDecodedBodySync((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(HttpDecodedResponse httpDecodedResponse, Throwable throwable, Context tracingContext) { if (tracingContext == null) { return; } Object disableTracingValue = (tracingContext.getData(Tracer.DISABLE_TRACING_KEY).isPresent() ? tracingContext.getData(Tracer.DISABLE_TRACING_KEY).get() : null); boolean disableTracing = Boolean.TRUE.equals(disableTracingValue != null ? disableTracingValue : false); if (disableTracing) { return; } int statusCode = 0; if (httpDecodedResponse != null) { statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (throwable != null) { if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
```suggestion throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); ```
void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } }
throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported.")));
void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSynchronously(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLength(request)); } final HttpResponse response = send(request, context); HttpDecodedResponse decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } } @SuppressWarnings("deprecation") static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); long length = binaryData.getLength(); if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, binaryData.getLength(), expectedLength), binaryData.getLength(), expectedLength); } return binaryData; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setContent(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setContent(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsByteArray().block(); if (responseBytes == null || responseBytes.length == 0) { throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().getBody().ignoreElements().block(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw new RuntimeException("Cannot find suitable constructor for class " + cls); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getContent().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getContent(); } else { result = response.getDecodedBody((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSync(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); final SwaggerMethodParser methodParser = getMethodParser(method); HttpRequest request; try { request = createHttpRequest(methodParser, args); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); HttpDecodedResponse decodedResponse = null; Throwable throwable = null; try { context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLengthSync(request)); } final HttpResponse response = send(request, context); decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (Exception e) { throwable = e; if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } finally { if (decodedResponse != null || throwable != null) { endTracingSpan(decodedResponse, throwable, context); } } } @SuppressWarnings("deprecation") static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } Exception e; byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsBinaryData().toBytes(); if (responseBytes == null || responseBytes.length == 0) { e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody); } if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().close(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getBodyAsBinaryData().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getBodyAsBinaryData(); } else { result = response.getDecodedBodySync((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(HttpDecodedResponse httpDecodedResponse, Throwable throwable, Context tracingContext) { if (tracingContext == null) { return; } Object disableTracingValue = (tracingContext.getData(Tracer.DISABLE_TRACING_KEY).isPresent() ? tracingContext.getData(Tracer.DISABLE_TRACING_KEY).get() : null); boolean disableTracing = Boolean.TRUE.equals(disableTracingValue != null ? disableTracingValue : false); if (disableTracing) { return; } int statusCode = 0; if (httpDecodedResponse != null) { statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (throwable != null) { if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
should we be calling into `validateLengthSync` here?
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLength(request)); } final HttpResponse response = send(request, context); HttpDecodedResponse decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } }
}
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); final SwaggerMethodParser methodParser = getMethodParser(method); HttpRequest request; try { request = createHttpRequest(methodParser, args); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); HttpDecodedResponse decodedResponse = null; Throwable throwable = null; try { context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLengthSync(request)); } final HttpResponse response = send(request, context); decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (Exception e) { throwable = e; if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } finally { if (decodedResponse != null || throwable != null) { endTracingSpan(decodedResponse, throwable, context); } } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSynchronously(request, contextData); } @Override @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); long length = binaryData.getLength(); if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, binaryData.getLength(), expectedLength), binaryData.getLength(), expectedLength); } return binaryData; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setContent(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setContent(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsByteArray().block(); if (responseBytes == null || responseBytes.length == 0) { throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().getBody().ignoreElements().block(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw new RuntimeException("Cannot find suitable constructor for class " + cls); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getContent().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getContent(); } else { result = response.getDecodedBody((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSync(request, contextData); } @Override @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } Exception e; byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsBinaryData().toBytes(); if (responseBytes == null || responseBytes.length == 0) { e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody); } if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().close(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getBodyAsBinaryData().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getBodyAsBinaryData(); } else { result = response.getDecodedBodySync((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(HttpDecodedResponse httpDecodedResponse, Throwable throwable, Context tracingContext) { if (tracingContext == null) { return; } Object disableTracingValue = (tracingContext.getData(Tracer.DISABLE_TRACING_KEY).isPresent() ? tracingContext.getData(Tracer.DISABLE_TRACING_KEY).get() : null); boolean disableTracing = Boolean.TRUE.equals(disableTracingValue != null ? disableTracingValue : false); if (disableTracing) { return; } int statusCode = 0; if (httpDecodedResponse != null) { statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (throwable != null) { if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
I wonder if a better option is to add metadata that tracks if the method called was synchronous or asynchronous into SwaggerMethodParser. This may also help simplify future work with regards of client telemetry that is sent including information such as whether the service client method called was sync or async. Additionally, this may allow us to continue using a single InvocationHandler implementation (RestProxy) instead of having a split path for sync vs async
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLength(request)); } final HttpResponse response = send(request, context); HttpDecodedResponse decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } }
final SwaggerMethodParser methodParser = getMethodParser(method);
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); final SwaggerMethodParser methodParser = getMethodParser(method); HttpRequest request; try { request = createHttpRequest(methodParser, args); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); HttpDecodedResponse decodedResponse = null; Throwable throwable = null; try { context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLengthSync(request)); } final HttpResponse response = send(request, context); decodedResponse = this.decoder.decodeSync(response, methodParser); return handleRestReturnType(decodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (Exception e) { throwable = e; if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } finally { if (decodedResponse != null || throwable != null) { endTracingSpan(decodedResponse, throwable, context); } } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSynchronously(request, contextData); } @Override @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); long length = binaryData.getLength(); if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, binaryData.getLength(), expectedLength), binaryData.getLength(), expectedLength); } return binaryData; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setContent(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setContent(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsByteArray().block(); if (responseBytes == null || responseBytes.length == 0) { throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); throw new RuntimeException(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().getBody().ignoreElements().block(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw new RuntimeException("Cannot find suitable constructor for class " + cls); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getContent().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getContent(); } else { result = response.getDecodedBody((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class SyncRestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private static final ClientLogger LOGGER = new ClientLogger(SyncRestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private SyncRestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public HttpResponse send(HttpRequest request, Context contextData) { return httpPipeline.sendSync(request, contextData); } @Override @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { context = CoreUtils.mergeContexts(context, optionsContext); } return context; } static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(BinaryData.fromStream(new ByteArrayInputStream(stream.toByteArray(), 0, stream.size()))); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(((ByteBuffer) bodyContentObject).array()); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(stream.toByteArray()); } } return request; } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private HttpDecodedResponse ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return decodedResponse; } Exception e; byte[] responseBytes = decodedResponse.getSourceResponse().getBodyAsBinaryData().toBytes(); if (responseBytes == null || responseBytes.length == 0) { e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null); } else { Object decodedBody = decodedResponse.getDecodedBodySync(responseBytes); e = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody); } if (e instanceof RuntimeException) { throw LOGGER.logExceptionAsError((RuntimeException) e); } else { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } private Object handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { response.getSourceResponse().close(); return createResponseSync(response, entityType, null); } else { Object bodyAsObject = handleBodyReturnTypeSync(response, methodParser, bodyType); Response<?> httpResponse = createResponseSync(response, entityType, bodyAsObject); if (httpResponse == null) { return createResponseSync(response, entityType, null); } return httpResponse; } } else { return handleBodyReturnTypeSync(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Response<?> createResponseSync(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); final HttpResponse httpResponse = response.getSourceResponse(); final HttpRequest request = httpResponse.getRequest(); final int statusCode = httpResponse.getStatusCode(); final HttpHeaders headers = httpResponse.getHeaders(); final Object decodedHeaders = response.getDecodedHeaders(); if (cls.equals(Response.class)) { return cls.cast(new ResponseBase<>(request, statusCode, headers, bodyAsObject, decodedHeaders)); } else if (cls.equals(PagedResponse.class)) { if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw LOGGER.logExceptionAsError(new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } else if (bodyAsObject == null) { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, null, null, decodedHeaders))); } else { return (cls.cast(new PagedResponseBase<>(request, statusCode, headers, (Page<?>) bodyAsObject, decodedHeaders))); } } MethodHandle ctr = RESPONSE_CONSTRUCTORS_CACHE.get(cls); if (ctr == null) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } return RESPONSE_CONSTRUCTORS_CACHE.invokeSync(ctr, response, bodyAsObject); } private Object handleBodyReturnTypeSync(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Object result; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; result = isSuccess; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { byte[] responseBodyBytes = response.getSourceResponse().getBodyAsBinaryData().toBytes(); if (returnValueWireType == Base64Url.class) { responseBodyBytes = new Base64Url(responseBodyBytes).decodedBytes(); } result = responseBodyBytes; } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { result = response.getSourceResponse().getBodyAsBinaryData(); } else { result = response.getDecodedBodySync((byte[]) null); } return result; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param httpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final HttpDecodedResponse httpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final HttpDecodedResponse expectedResponse = ensureExpectedStatus(httpDecodedResponse, methodParser, options); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { result = expectedResponse; } else { result = handleRestResponseReturnType(httpDecodedResponse, methodParser, returnType); } return result; } private static void endTracingSpan(HttpDecodedResponse httpDecodedResponse, Throwable throwable, Context tracingContext) { if (tracingContext == null) { return; } Object disableTracingValue = (tracingContext.getData(Tracer.DISABLE_TRACING_KEY).isPresent() ? tracingContext.getData(Tracer.DISABLE_TRACING_KEY).get() : null); boolean disableTracing = Boolean.TRUE.equals(disableTracingValue != null ? disableTracingValue : false); if (disableTracing) { return; } int statusCode = 0; if (httpDecodedResponse != null) { statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (throwable != null) { if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final SyncRestProxy restProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
I'd lean towards throwing when synchronous APIs are trying to send asynchronous payloads. And I think we're better off with having BinaryDataContent handling length validation instead of potentially having it crop up in many different spots in code (and likely having slightly skewed implementations, such as we've seen with InputStream -> Flux<ByteBuffer> conversions within the repo)
static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); long length = binaryData.getLength(); if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, binaryData.getLength(), expectedLength), binaryData.getLength(), expectedLength); } return binaryData; }
long length = binaryData.getLength();
static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } }
class is if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); }
class is if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); }
Don't we also need to check if length is less than the expected length?
static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); long length = binaryData.getLength(); if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, binaryData.getLength(), expectedLength), binaryData.getLength(), expectedLength); } return binaryData; }
if (length > expectedLength) {
static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } }
class is if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); }
class is if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); }
we shouldn't eagerly read the stream here. Rather substitute request body with wrapped stream and the validation will happen lazily when stream is read. See https://github.com/Azure/azure-sdk-for-java/blob/400e90a8ceced0f0ad5d586532db6637d29b45d6/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/LengthValidatingInputStream.java#L48 .
static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getContent(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(((InputStreamContent) bdc).toStream(), expectedLength); try { lengthValidatingInputStream.readAllBytes(); } catch (IOException e) { throw new UncheckedIOException(e); } } else { long len = (bdc).toBytes().length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } } } return binaryData; }
lengthValidatingInputStream.readAllBytes();
static BinaryData validateLengthSync(final HttpRequest request) { final BinaryData binaryData = request.getBodyAsBinaryData(); if (binaryData == null) { return binaryData; } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); Long length = binaryData.getLength(); BinaryDataContent bdc = BinaryDataHelper.getContent(binaryData); if (length == null) { if (bdc instanceof FluxByteBufferContent) { throw new IllegalStateException("Flux Byte Buffer is not supported in Synchronous Rest Proxy."); } else if (bdc instanceof InputStreamContent) { InputStreamContent inputStreamContent = ((InputStreamContent) bdc); InputStream inputStream = inputStreamContent.toStream(); LengthValidatingInputStream lengthValidatingInputStream = new LengthValidatingInputStream(inputStream, expectedLength); return BinaryData.fromStream(lengthValidatingInputStream); } else { byte[] b = (bdc).toBytes(); long len = b.length; if (len > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, len, expectedLength), len, expectedLength); } return BinaryData.fromBytes(b); } } else { if (length > expectedLength) { throw new UnexpectedLengthException(String.format(BODY_TOO_LARGE, length, expectedLength), length, expectedLength); } return binaryData; } }
class is if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); }
class is if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw LOGGER.logExceptionAsError(new IllegalStateException("'ResumeOperation' isn't supported.")); }
should we expose this as an option or configuration property? I case somebody took dependency on this somehow.
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(false); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
httpClientBuilder.followRedirects(false);
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
If an external customer took dependency on it, we are going to break them never the less if we change the default settings. If they have to change their code we might as well recommend them to add redirect policy. For our SDKs - we support both Netty and OkHttp AFAIK. Since Netty does not handle redirects by default an SDK is less likely to hit this.
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(false); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
httpClientBuilder.followRedirects(false);
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
We usually offer some compat switch for behavior breaking changes like this so that customers can bring back old behavior with least effort. Config switch is usually easiest one as it doesn't require code change in case of emergency. If we think that adding redirect policy is acceptable easy solution then we should at least document mitigation steps in changelog when calling out this change.
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(false); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
httpClientBuilder.followRedirects(false);
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
That is a fair point. I am not sure which of the 2 options should we choose it likely depends on how popular OkHttpClient is for our customers. /cc: @srnagar , @JonathanGiles
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(false); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
httpClientBuilder.followRedirects(false);
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
Given that OkHttpClientBuilder allows you to [create a client from an instance of `OkHttpClient`](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-http-okhttp/src/main/java/com/azure/core/http/okhttp/OkHttpAsyncHttpClientBuilder.java#L72) directly, users who want this behavior can configure their own OkHttpClient with automatic redirection enabled and create the builder. Given that OkHttp is not the default client and isn't widely used, compat switch may not be required.
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(false); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
httpClientBuilder.followRedirects(false);
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
Updated the changelog.
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(false); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
httpClientBuilder.followRedirects(false);
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
The behavior via [create a client from an instance of OkHttpClient](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-http-okhttp/src/main/java/com/azure/core/http/okhttp/OkHttpAsyncHttpClientBuilder.java#L72) is not correct. We override the values set on the OkHttpClientBuilder in our builder which seems like an oversight and something we should fix. I will create a bug to do this separately. In order to support the current scenario I am exposing a new property so someone who depends on the older behavior has a fallback in place.
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(false); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
httpClientBuilder.followRedirects(false);
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
Couldn't this just be ```suggestion httpClientBuilder.followRedirects(followRedirects); ``` since `boolean` is false by default #Resolved
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } if (!this.followRedirects) { httpClientBuilder.followRedirects(false); } return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
}
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}. * * If this policy is set to 'true' OkHttp-backed {@link com.azure.core.http.HttpClient} will follow redirects automatically * If your HTTP pipeline is configured to call redirect policy it will not be called if this value is true. * * @param followRedirect Whether OKHttpClient should follow redirects by default. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirect) { this.followRedirects = followRedirect; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
Yes :D
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } if (!this.followRedirects) { httpClientBuilder.followRedirects(false); } return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
}
public HttpClient build() { OkHttpClient.Builder httpClientBuilder = this.okHttpClient == null ? new OkHttpClient.Builder() : this.okHttpClient.newBuilder(); for (Interceptor interceptor : this.networkInterceptors) { httpClientBuilder = httpClientBuilder.addNetworkInterceptor(interceptor); } httpClientBuilder = httpClientBuilder .connectTimeout(getTimeoutMillis(connectionTimeout, DEFAULT_CONNECT_TIMEOUT), TimeUnit.MILLISECONDS) .writeTimeout(getTimeoutMillis(writeTimeout, DEFAULT_WRITE_TIMEOUT), TimeUnit.MILLISECONDS) .readTimeout(getTimeoutMillis(readTimeout, DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS); if (this.connectionPool != null) { httpClientBuilder = httpClientBuilder.connectionPool(connectionPool); } if (this.dispatcher != null) { httpClientBuilder = httpClientBuilder.dispatcher(dispatcher); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { httpClientBuilder = httpClientBuilder.proxySelector(new OkHttpProxySelector( buildProxyOptions.getType().toProxyType(), buildProxyOptions::getAddress, buildProxyOptions.getNonProxyHosts())); if (buildProxyOptions.getUsername() != null) { ProxyAuthenticator proxyAuthenticator = new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()); httpClientBuilder = httpClientBuilder.proxyAuthenticator(proxyAuthenticator) .addInterceptor(proxyAuthenticator.getProxyAuthenticationInfoInterceptor()); } } httpClientBuilder.followRedirects(this.followRedirects); return new OkHttpAsyncHttpClient(httpClientBuilder.build()); }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}. * * If this policy is set to 'true' OkHttp-backed {@link com.azure.core.http.HttpClient} will follow redirects automatically * If your HTTP pipeline is configured to call redirect policy it will not be called if this value is true. * * @param followRedirect Whether OKHttpClient should follow redirects by default. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirect) { this.followRedirects = followRedirect; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
class OkHttpAsyncHttpClientBuilder { private final okhttp3.OkHttpClient okHttpClient; private static final long MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_TIMEOUT; private static final long DEFAULT_WRITE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; static { ClientLogger logger = new ClientLogger(OkHttpAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); } private List<Interceptor> networkInterceptors = new ArrayList<>(); private Duration readTimeout; private Duration writeTimeout; private Duration connectionTimeout; private ConnectionPool connectionPool; private Dispatcher dispatcher; private ProxyOptions proxyOptions; private Configuration configuration; private boolean followRedirects; /** * Creates OkHttpAsyncHttpClientBuilder. */ public OkHttpAsyncHttpClientBuilder() { this.okHttpClient = null; } /** * Creates OkHttpAsyncHttpClientBuilder from the builder of an existing OkHttpClient. * * @param okHttpClient the httpclient */ public OkHttpAsyncHttpClientBuilder(OkHttpClient okHttpClient) { this.okHttpClient = Objects.requireNonNull(okHttpClient, "'okHttpClient' cannot be null."); } /** * Add a network layer interceptor to Http request pipeline. * * @param networkInterceptor the interceptor to add * @return the updated OkHttpAsyncHttpClientBuilder object */ public OkHttpAsyncHttpClientBuilder addNetworkInterceptor(Interceptor networkInterceptor) { Objects.requireNonNull(networkInterceptor, "'networkInterceptor' cannot be null."); this.networkInterceptors.add(networkInterceptor); return this; } /** * Add network layer interceptors to Http request pipeline. * <p> * This replaces all previously-set interceptors. * * @param networkInterceptors The interceptors to add. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder networkInterceptors(List<Interceptor> networkInterceptors) { this.networkInterceptors = Objects.requireNonNull(networkInterceptors, "'networkInterceptors' cannot be null."); return this; } /** * Sets the read timeout duration used when reading the server response. * <p> * The read timeout begins once the first response read is triggered after the server response is received. This * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. * <p> * If {@code readTimeout} is null or {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. * * @param readTimeout Read timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } /** * Sets the writing timeout for a request to be sent. * <p> * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. * <p> * If {@code writeTimeout} is null either {@link Configuration * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. * * @param writeTimeout Write operation timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * Sets the connection timeout for a request to be sent. * <p> * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. * <p> * If {@code connectTimeout} is null either {@link Configuration * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. * <p> * By default the connection timeout is 10 seconds. * * @param connectionTimeout Connect timeout duration. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Sets the Http connection pool. * * @param connectionPool The OkHttp connection pool to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder connectionPool(ConnectionPool connectionPool) { this.connectionPool = Objects.requireNonNull(connectionPool, "'connectionPool' cannot be null."); return this; } /** * Sets the dispatcher that also composes the thread pool for executing HTTP requests. * * @param dispatcher The dispatcher to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder dispatcher(Dispatcher dispatcher) { this.dispatcher = Objects.requireNonNull(dispatcher, "'dispatcher' cannot be null."); return this; } /** * Sets the proxy. * * @param proxyOptions The proxy configuration to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the configuration store that is used during construction of the HTTP client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * <p>Sets the followRedirect flag on the underlying OkHttp-backed {@link com.azure.core.http.HttpClient}.</p> * * <p>If this is set to 'true' redirects will be followed automatically, and * if your HTTP pipeline is configured with a redirect policy it will not be called.</p> * * @param followRedirects The followRedirects value to use. * @return The updated OkHttpAsyncHttpClientBuilder object. */ public OkHttpAsyncHttpClientBuilder followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } /** * Creates a new OkHttp-backed {@link com.azure.core.http.HttpClient} instance on every call, using the * configuration set in the builder at the time of the build method call. * * @return A new OkHttp-backed {@link com.azure.core.http.HttpClient} instance. */ /* * Returns the timeout in milliseconds to use based on the passed Duration and default timeout. * * If the timeout is {@code null} the default timeout will be used. If the timeout is less than or equal to zero * no timeout will be used. If the timeout is less than one millisecond a timeout of one millisecond will be used. */ static long getTimeoutMillis(Duration configuredTimeout, long defaultTimeout) { if (configuredTimeout == null) { return defaultTimeout; } if (configuredTimeout.isZero() || configuredTimeout.isNegative()) { return 0; } return Math.max(configuredTimeout.toMillis(), MINIMUM_TIMEOUT); } }
NOTE: Overrides the client assertion at per request level.
public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); }
if (clientAssertionSupplier != null) {
public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); }
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 Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * 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 resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(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.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { 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(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, 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) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(null, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append("--tenant ").append(tenant); } AccessToken token; 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, azCommand.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. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); 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 AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * 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 */ 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 publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * 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 */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * 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 publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio 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) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * 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) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * 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 * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.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(LoggingUtil.logCredentialUnavailableException(LOGGER, options, 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 Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = new URL(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = new URL(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = new URL(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI 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 identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = new URL(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } 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", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("%s?%s", endpoint, payload)); 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() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } 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(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "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 input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } 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, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
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 Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); private static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String resourceId; private final String clientSecret; private final String clientAssertionFilePath; private final InputStream certificate; private final String certificatePath; private final Supplier<String> clientAssertionSupplier; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * 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 resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication()); this.clientAssertionAccessor = clientAssertionTimeout == null ? new SynchronizedAccessor<>(() -> parseClientAssertion(), Duration.ofMinutes(5)) : new SynchronizedAccessor<>(() -> parseClientAssertion(), clientAssertionTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(LOGGER.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(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.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE."))); } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { 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(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, 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) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); String tenant = IdentityUtil.resolveTenantId(null, request, options); if (!CoreUtils.isNullOrEmpty(tenant)) { azCommand.append("--tenant ").append(tenant); } AccessToken token; 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, azCommand.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. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8.name()))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); 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 AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build())) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return manager.runCommand(azAccountsCommand) .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to" + " use Azure PowerShell Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); String command = accessTokenCommand.toString(); LOGGER.verbose("Azure Powershell Authentication => Executing the command `%s` in Azure " + "Powershell to retrieve the Access Token.", accessTokenCommand); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }).doFinally(ignored -> powershellManager.close()); } /** * 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 */ 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 publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } forceParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * 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 */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * 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 publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio 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) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * 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) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * 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 * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.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(LoggingUtil.logCredentialUnavailableException(LOGGER, options, 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 Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", StandardCharsets.UTF_8.name())); URL url = new URL(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId + "/oauth2/v2.0/token"; StringBuilder urlParametersBuilder = new StringBuilder(); urlParametersBuilder.append("client_assertion="); urlParametersBuilder.append(assertionToken); urlParametersBuilder.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type" + ":jwt-bearer"); urlParametersBuilder.append("&client_id="); urlParametersBuilder.append(clientId); urlParametersBuilder.append("&grant_type=client_credentials"); urlParametersBuilder.append("&scope="); urlParametersBuilder.append(URLEncoder.encode(request.getScopes().get(0), StandardCharsets.UTF_8.name())); String urlParams = urlParametersBuilder.toString(); byte[] postData = urlParams.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; HttpURLConnection connection = null; URL url = new URL(authorityUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.write(postData); } connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } })); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = new URL(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI 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 identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } try { URL url = new URL(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } 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", StandardCharsets.UTF_8.name())); payload.append("&resource="); payload.append(URLEncoder.encode(resource, StandardCharsets.UTF_8.name())); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, StandardCharsets.UTF_8.name())); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(URLEncoder.encode(resourceId, StandardCharsets.UTF_8.name())); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("%s?%s", endpoint, payload)); 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() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } 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(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", StandardCharsets.UTF_8.name())); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("%s?%s", endpoint, payload)); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "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 input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } 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, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } }
Does `headerName` need to be passed as an array? #Resolved
String tryGetRedirectHeader(HttpHeaders headers, String headerName) { String headerValue = headers.getValue(headerName); if (CoreUtils.isNullOrEmpty(headerValue)) { LOGGER.error("Redirect url was null for header name: {}, request redirect was terminated.", new Object[]{headerName}); return null; } else { return headerValue; } }
LOGGER.error("Redirect url was null for header name: {}, request redirect was terminated.", new Object[]{headerName});
String tryGetRedirectHeader(HttpHeaders headers, String headerName) { String headerValue = headers.getValue(headerName); if (CoreUtils.isNullOrEmpty(headerValue)) { LOGGER.error("Redirect url was null for header name: {}, request redirect was terminated.", headerName); return null; } else { return headerValue; } }
class ContainerRegistryRedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(com.azure.core.http.policy.DefaultRedirectStrategy.class); private static final int MAX_REDIRECT_ATTEMPTS; private static final String REDIRECT_LOCATION_HEADER_NAME; private static final int PERMANENT_REDIRECT_STATUS_CODE; private static final int TEMPORARY_REDIRECT_STATUS_CODE; private static final Set<HttpMethod> REDIRECT_ALLOWED_METHODS; private static final String AUTHORIZATION; static { REDIRECT_ALLOWED_METHODS = new HashSet<>(Arrays.asList(HttpMethod.GET, HttpMethod.HEAD)); PERMANENT_REDIRECT_STATUS_CODE = 308; TEMPORARY_REDIRECT_STATUS_CODE = 307; REDIRECT_LOCATION_HEADER_NAME = "Location"; MAX_REDIRECT_ATTEMPTS = 3; AUTHORIZATION = "Authorization"; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return this.attemptRedirect(context, next, context.getHttpRequest(), 1, new HashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline * and redirect sending the request with new redirect url. */ private Mono<HttpResponse> attemptRedirect(HttpPipelineCallContext context, HttpPipelineNextPolicy next, HttpRequest originalHttpRequest, int redirectAttempt, Set<String> attemptedRedirectUrls) { context.setHttpRequest(originalHttpRequest.copy()); return next.clone().process().flatMap((httpResponse) -> { if (this.shouldAttemptRedirect(context, httpResponse, redirectAttempt, attemptedRedirectUrls)) { HttpRequest redirectRequestCopy = this.createRedirectRequest(httpResponse); return httpResponse.getBody().ignoreElements() .then(this.attemptRedirect(context, next, redirectRequestCopy, redirectAttempt + 1, attemptedRedirectUrls)) .flatMap(newResponse -> { String digest = httpResponse.getHeaders().getValue(DOCKER_DIGEST_HEADER_NAME); if (digest != null) { newResponse.getHeaders().add(DOCKER_DIGEST_HEADER_NAME, digest); } return Mono.just(newResponse); }); } else { return Mono.just(httpResponse); } }); } public boolean shouldAttemptRedirect(HttpPipelineCallContext context, HttpResponse httpResponse, int tryCount, Set<String> attemptedRedirectUrls) { if (this.isValidRedirectStatusCode(httpResponse.getStatusCode()) && this.isValidRedirectCount(tryCount) && this.isAllowedRedirectMethod(httpResponse.getRequest().getHttpMethod())) { String redirectUrl = this.tryGetRedirectHeader(httpResponse.getHeaders(), REDIRECT_LOCATION_HEADER_NAME); if (redirectUrl != null && !this.alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.verbose("[Redirecting] Try count: {}, Attempted Redirect URLs: {}", new Object[]{tryCount, attemptedRedirectUrls.toString()}); attemptedRedirectUrls.add(redirectUrl); return true; } else { return false; } } else { return false; } } private HttpRequest createRedirectRequest(HttpResponse httpResponse) { String responseLocation = this.tryGetRedirectHeader(httpResponse.getHeaders(), REDIRECT_LOCATION_HEADER_NAME); HttpRequest request = httpResponse.getRequest(); request.setUrl(responseLocation); request.getHeaders().remove(AUTHORIZATION); return httpResponse.getRequest().setUrl(responseLocation); } private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.error("Request was redirected more than once to: {}", new Object[]{redirectUrl}); return true; } else { return false; } } private boolean isValidRedirectCount(int tryCount) { if (tryCount >= MAX_REDIRECT_ATTEMPTS) { LOGGER.error("Request has been redirected more than {} times.", new Object[]{MAX_REDIRECT_ATTEMPTS}); return false; } else { return true; } } private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (REDIRECT_ALLOWED_METHODS.contains(httpMethod)) { return true; } else { LOGGER.error("Request was redirected from an invalid redirect allowed method: {}", new Object[]{httpMethod}); return false; } } private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } }
class ContainerRegistryRedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(com.azure.core.http.policy.DefaultRedirectStrategy.class); private static final int MAX_REDIRECT_ATTEMPTS; private static final String REDIRECT_LOCATION_HEADER_NAME; private static final int PERMANENT_REDIRECT_STATUS_CODE; private static final int TEMPORARY_REDIRECT_STATUS_CODE; private static final Set<HttpMethod> REDIRECT_ALLOWED_METHODS; private static final String AUTHORIZATION; static { REDIRECT_ALLOWED_METHODS = new HashSet<>(Arrays.asList(HttpMethod.GET, HttpMethod.HEAD)); PERMANENT_REDIRECT_STATUS_CODE = 308; TEMPORARY_REDIRECT_STATUS_CODE = 307; REDIRECT_LOCATION_HEADER_NAME = "Location"; MAX_REDIRECT_ATTEMPTS = 3; AUTHORIZATION = "Authorization"; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return this.attemptRedirect(context, next, context.getHttpRequest(), 1, new HashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline * and redirect sending the request with new redirect url. */ private Mono<HttpResponse> attemptRedirect(HttpPipelineCallContext context, HttpPipelineNextPolicy next, HttpRequest originalHttpRequest, int redirectAttempt, Set<String> attemptedRedirectUrls) { context.setHttpRequest(originalHttpRequest.copy()); return next.clone().process().flatMap((httpResponse) -> { if (this.shouldAttemptRedirect(context, httpResponse, redirectAttempt, attemptedRedirectUrls)) { HttpRequest redirectRequestCopy = this.createRedirectRequest(httpResponse); return httpResponse.getBody().ignoreElements() .then(this.attemptRedirect(context, next, redirectRequestCopy, redirectAttempt + 1, attemptedRedirectUrls)) .flatMap(newResponse -> { String digest = httpResponse.getHeaders().getValue(DOCKER_DIGEST_HEADER_NAME); if (digest != null) { newResponse.getHeaders().add(DOCKER_DIGEST_HEADER_NAME, digest); } return Mono.just(newResponse); }); } else { return Mono.just(httpResponse); } }); } public boolean shouldAttemptRedirect(HttpPipelineCallContext context, HttpResponse httpResponse, int tryCount, Set<String> attemptedRedirectUrls) { if (this.isValidRedirectStatusCode(httpResponse.getStatusCode()) && this.isValidRedirectCount(tryCount) && this.isAllowedRedirectMethod(httpResponse.getRequest().getHttpMethod())) { String redirectUrl = this.tryGetRedirectHeader(httpResponse.getHeaders(), REDIRECT_LOCATION_HEADER_NAME); if (redirectUrl != null && !this.alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.verbose("[Redirecting] Try count: {}, Attempted Redirect URLs: {}", tryCount, String.join(",", attemptedRedirectUrls)); attemptedRedirectUrls.add(redirectUrl); return true; } else { return false; } } else { return false; } } private HttpRequest createRedirectRequest(HttpResponse httpResponse) { String responseLocation = this.tryGetRedirectHeader(httpResponse.getHeaders(), REDIRECT_LOCATION_HEADER_NAME); HttpRequest request = httpResponse.getRequest(); request.setUrl(responseLocation); request.getHeaders().remove(AUTHORIZATION); return httpResponse.getRequest().setUrl(responseLocation); } private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.error("Request was redirected more than once to: {}", new Object[]{redirectUrl}); return true; } else { return false; } } private boolean isValidRedirectCount(int tryCount) { if (tryCount >= MAX_REDIRECT_ATTEMPTS) { LOGGER.error("Request has been redirected more than {} times.", new Object[]{MAX_REDIRECT_ATTEMPTS}); return false; } else { return true; } } private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (REDIRECT_ALLOWED_METHODS.contains(httpMethod)) { return true; } else { LOGGER.error("Request was redirected from an invalid redirect allowed method: {}", new Object[]{httpMethod}); return false; } } private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } }
nit: Don't use toString in a log variable #Resolved
public boolean shouldAttemptRedirect(HttpPipelineCallContext context, HttpResponse httpResponse, int tryCount, Set<String> attemptedRedirectUrls) { if (this.isValidRedirectStatusCode(httpResponse.getStatusCode()) && this.isValidRedirectCount(tryCount) && this.isAllowedRedirectMethod(httpResponse.getRequest().getHttpMethod())) { String redirectUrl = this.tryGetRedirectHeader(httpResponse.getHeaders(), REDIRECT_LOCATION_HEADER_NAME); if (redirectUrl != null && !this.alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.verbose("[Redirecting] Try count: {}, Attempted Redirect URLs: {}", new Object[]{tryCount, attemptedRedirectUrls.toString()}); attemptedRedirectUrls.add(redirectUrl); return true; } else { return false; } } else { return false; } }
LOGGER.verbose("[Redirecting] Try count: {}, Attempted Redirect URLs: {}", new Object[]{tryCount, attemptedRedirectUrls.toString()});
public boolean shouldAttemptRedirect(HttpPipelineCallContext context, HttpResponse httpResponse, int tryCount, Set<String> attemptedRedirectUrls) { if (this.isValidRedirectStatusCode(httpResponse.getStatusCode()) && this.isValidRedirectCount(tryCount) && this.isAllowedRedirectMethod(httpResponse.getRequest().getHttpMethod())) { String redirectUrl = this.tryGetRedirectHeader(httpResponse.getHeaders(), REDIRECT_LOCATION_HEADER_NAME); if (redirectUrl != null && !this.alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.verbose("[Redirecting] Try count: {}, Attempted Redirect URLs: {}", tryCount, String.join(",", attemptedRedirectUrls)); attemptedRedirectUrls.add(redirectUrl); return true; } else { return false; } } else { return false; } }
class ContainerRegistryRedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(com.azure.core.http.policy.DefaultRedirectStrategy.class); private static final int MAX_REDIRECT_ATTEMPTS; private static final String REDIRECT_LOCATION_HEADER_NAME; private static final int PERMANENT_REDIRECT_STATUS_CODE; private static final int TEMPORARY_REDIRECT_STATUS_CODE; private static final Set<HttpMethod> REDIRECT_ALLOWED_METHODS; private static final String AUTHORIZATION; static { REDIRECT_ALLOWED_METHODS = new HashSet<>(Arrays.asList(HttpMethod.GET, HttpMethod.HEAD)); PERMANENT_REDIRECT_STATUS_CODE = 308; TEMPORARY_REDIRECT_STATUS_CODE = 307; REDIRECT_LOCATION_HEADER_NAME = "Location"; MAX_REDIRECT_ATTEMPTS = 3; AUTHORIZATION = "Authorization"; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return this.attemptRedirect(context, next, context.getHttpRequest(), 1, new HashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline * and redirect sending the request with new redirect url. */ private Mono<HttpResponse> attemptRedirect(HttpPipelineCallContext context, HttpPipelineNextPolicy next, HttpRequest originalHttpRequest, int redirectAttempt, Set<String> attemptedRedirectUrls) { context.setHttpRequest(originalHttpRequest.copy()); return next.clone().process().flatMap((httpResponse) -> { if (this.shouldAttemptRedirect(context, httpResponse, redirectAttempt, attemptedRedirectUrls)) { HttpRequest redirectRequestCopy = this.createRedirectRequest(httpResponse); return httpResponse.getBody().ignoreElements() .then(this.attemptRedirect(context, next, redirectRequestCopy, redirectAttempt + 1, attemptedRedirectUrls)) .flatMap(newResponse -> { String digest = httpResponse.getHeaders().getValue(DOCKER_DIGEST_HEADER_NAME); if (digest != null) { newResponse.getHeaders().add(DOCKER_DIGEST_HEADER_NAME, digest); } return Mono.just(newResponse); }); } else { return Mono.just(httpResponse); } }); } private HttpRequest createRedirectRequest(HttpResponse httpResponse) { String responseLocation = this.tryGetRedirectHeader(httpResponse.getHeaders(), REDIRECT_LOCATION_HEADER_NAME); HttpRequest request = httpResponse.getRequest(); request.setUrl(responseLocation); request.getHeaders().remove(AUTHORIZATION); return httpResponse.getRequest().setUrl(responseLocation); } private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.error("Request was redirected more than once to: {}", new Object[]{redirectUrl}); return true; } else { return false; } } private boolean isValidRedirectCount(int tryCount) { if (tryCount >= MAX_REDIRECT_ATTEMPTS) { LOGGER.error("Request has been redirected more than {} times.", new Object[]{MAX_REDIRECT_ATTEMPTS}); return false; } else { return true; } } private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (REDIRECT_ALLOWED_METHODS.contains(httpMethod)) { return true; } else { LOGGER.error("Request was redirected from an invalid redirect allowed method: {}", new Object[]{httpMethod}); return false; } } private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } String tryGetRedirectHeader(HttpHeaders headers, String headerName) { String headerValue = headers.getValue(headerName); if (CoreUtils.isNullOrEmpty(headerValue)) { LOGGER.error("Redirect url was null for header name: {}, request redirect was terminated.", new Object[]{headerName}); return null; } else { return headerValue; } } }
class ContainerRegistryRedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(com.azure.core.http.policy.DefaultRedirectStrategy.class); private static final int MAX_REDIRECT_ATTEMPTS; private static final String REDIRECT_LOCATION_HEADER_NAME; private static final int PERMANENT_REDIRECT_STATUS_CODE; private static final int TEMPORARY_REDIRECT_STATUS_CODE; private static final Set<HttpMethod> REDIRECT_ALLOWED_METHODS; private static final String AUTHORIZATION; static { REDIRECT_ALLOWED_METHODS = new HashSet<>(Arrays.asList(HttpMethod.GET, HttpMethod.HEAD)); PERMANENT_REDIRECT_STATUS_CODE = 308; TEMPORARY_REDIRECT_STATUS_CODE = 307; REDIRECT_LOCATION_HEADER_NAME = "Location"; MAX_REDIRECT_ATTEMPTS = 3; AUTHORIZATION = "Authorization"; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return this.attemptRedirect(context, next, context.getHttpRequest(), 1, new HashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline * and redirect sending the request with new redirect url. */ private Mono<HttpResponse> attemptRedirect(HttpPipelineCallContext context, HttpPipelineNextPolicy next, HttpRequest originalHttpRequest, int redirectAttempt, Set<String> attemptedRedirectUrls) { context.setHttpRequest(originalHttpRequest.copy()); return next.clone().process().flatMap((httpResponse) -> { if (this.shouldAttemptRedirect(context, httpResponse, redirectAttempt, attemptedRedirectUrls)) { HttpRequest redirectRequestCopy = this.createRedirectRequest(httpResponse); return httpResponse.getBody().ignoreElements() .then(this.attemptRedirect(context, next, redirectRequestCopy, redirectAttempt + 1, attemptedRedirectUrls)) .flatMap(newResponse -> { String digest = httpResponse.getHeaders().getValue(DOCKER_DIGEST_HEADER_NAME); if (digest != null) { newResponse.getHeaders().add(DOCKER_DIGEST_HEADER_NAME, digest); } return Mono.just(newResponse); }); } else { return Mono.just(httpResponse); } }); } private HttpRequest createRedirectRequest(HttpResponse httpResponse) { String responseLocation = this.tryGetRedirectHeader(httpResponse.getHeaders(), REDIRECT_LOCATION_HEADER_NAME); HttpRequest request = httpResponse.getRequest(); request.setUrl(responseLocation); request.getHeaders().remove(AUTHORIZATION); return httpResponse.getRequest().setUrl(responseLocation); } private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.error("Request was redirected more than once to: {}", new Object[]{redirectUrl}); return true; } else { return false; } } private boolean isValidRedirectCount(int tryCount) { if (tryCount >= MAX_REDIRECT_ATTEMPTS) { LOGGER.error("Request has been redirected more than {} times.", new Object[]{MAX_REDIRECT_ATTEMPTS}); return false; } else { return true; } } private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (REDIRECT_ALLOWED_METHODS.contains(httpMethod)) { return true; } else { LOGGER.error("Request was redirected from an invalid redirect allowed method: {}", new Object[]{httpMethod}); return false; } } private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } String tryGetRedirectHeader(HttpHeaders headers, String headerName) { String headerValue = headers.getValue(headerName); if (CoreUtils.isNullOrEmpty(headerValue)) { LOGGER.error("Redirect url was null for header name: {}, request redirect was terminated.", headerName); return null; } else { return headerValue; } } }
```suggestion return this.headers; ```
public HttpHeaders getHeaders() { return this.headers ; }
return this.headers ;
public HttpHeaders getHeaders() { return this.headers; }
class MockHttpResponse extends HttpResponse { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); private final int statusCode; private final HttpHeaders headers; private final byte[] bodyBytes; public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, byte[] bodyBytes) { super(request); this.statusCode = statusCode; this.headers = headers; this.bodyBytes = bodyBytes; } public MockHttpResponse(HttpRequest request, int statusCode) { this(request, statusCode, new HttpHeaders(), new byte[0]); } public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers) { this(request, statusCode, headers, new byte[0]); } public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, Object serializable) { this(request, statusCode, headers, serialize(serializable)); } public MockHttpResponse(HttpRequest request, int statusCode, Object serializable) { this(request, statusCode, new HttpHeaders(), serialize(serializable)); } private static byte[] serialize(Object serializable) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); SERIALIZER.serialize(serializable, SerializerEncoding.JSON, stream); return stream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes == null) { return Mono.empty(); } else { return Mono.just(bodyBytes); } } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes == null) { return Flux.empty(); } else { return Flux.just(ByteBuffer.wrap(bodyBytes)); } } @Override public Mono<String> getBodyAsString() { return getBodyAsString(StandardCharsets.UTF_8); } @Override public Mono<String> getBodyAsString(Charset charset) { if (bodyBytes == null) { return Mono.empty(); } else { return Mono.just(new String(bodyBytes, charset)); } } }
class MockHttpResponse extends HttpResponse { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); private final int statusCode; private final HttpHeaders headers; private final byte[] bodyBytes; public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, byte[] bodyBytes) { super(request); this.statusCode = statusCode; this.headers = headers; this.bodyBytes = bodyBytes; } public MockHttpResponse(HttpRequest request, int statusCode) { this(request, statusCode, new HttpHeaders(), new byte[0]); } public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers) { this(request, statusCode, headers, new byte[0]); } public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, Object serializable) { this(request, statusCode, headers, serialize(serializable)); } public MockHttpResponse(HttpRequest request, int statusCode, Object serializable) { this(request, statusCode, new HttpHeaders(), serialize(serializable)); } private static byte[] serialize(Object serializable) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); SERIALIZER.serialize(serializable, SerializerEncoding.JSON, stream); return stream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes == null) { return Mono.empty(); } else { return Mono.just(bodyBytes); } } @Override public Flux<ByteBuffer> getBody() { if (bodyBytes == null) { return Flux.empty(); } else { return Flux.just(ByteBuffer.wrap(bodyBytes)); } } @Override public Mono<String> getBodyAsString() { return getBodyAsString(StandardCharsets.UTF_8); } @Override public Mono<String> getBodyAsString(Charset charset) { if (bodyBytes == null) { return Mono.empty(); } else { return Mono.just(new String(bodyBytes, charset)); } } }
fwiw we should start using `HttpResponse.close` for this.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme")); } HttpPipelineNextPolicy nextPolicy = next.clone(); return authorizeRequest(context) .then(Mono.defer(() -> next.process())) .flatMap(httpResponse -> { String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE); if (httpResponse.getStatusCode() == 401 && authHeader != null) { return authorizeRequestOnChallenge(context, httpResponse).flatMap(retry -> { if (retry) { return httpResponse.getBody().ignoreElements() .then(nextPolicy.process()); } else { return Mono.just(httpResponse); } }); } return Mono.just(httpResponse); }); }
.then(nextPolicy.process());
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme")); } HttpPipelineNextPolicy nextPolicy = next.clone(); return authorizeRequest(context) .then(Mono.defer(() -> next.process())) .flatMap(httpResponse -> { String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE); if (httpResponse.getStatusCode() == 401 && authHeader != null) { return authorizeRequestOnChallenge(context, httpResponse).flatMap(retry -> { if (retry) { return httpResponse.getBody().ignoreElements() .then(nextPolicy.process()); } else { return Mono.just(httpResponse); } }); } return Mono.just(httpResponse); }); }
class BearerTokenAuthenticationPolicy implements HttpPipelinePolicy { private static final String AUTHORIZATION_HEADER = "Authorization"; private static final String BEARER = "Bearer"; private final String[] scopes; private final AccessTokenCache cache; /** * Creates BearerTokenAuthenticationPolicy. * * @param credential the token credential to authenticate the request * @param scopes the scopes of authentication the credential should get token for */ public BearerTokenAuthenticationPolicy(TokenCredential credential, String... scopes) { Objects.requireNonNull(credential); this.scopes = scopes; this.cache = new AccessTokenCache(credential); } /** * Executed before sending the initial request and authenticates the request. * * @param context The request context. * @return A {@link Mono} containing {@link Void} */ public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { if (this.scopes == null) { return Mono.empty(); } return setAuthorizationHeaderHelper(context, new TokenRequestContext().addScopes(this.scopes), false); } /** * Handles the authentication challenge in the event a 401 response with a WWW-Authenticate authentication * challenge header is received after the initial request and returns appropriate {@link TokenRequestContext} to * be used for re-authentication. * * @param context The request context. * @param response The Http Response containing the authentication challenge header. * @return A {@link Mono} containing {@link TokenRequestContext} */ public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.just(false); } @Override /** * Authorizes the request with the bearer token acquired using the specified {@code tokenRequestContext} * * @param context the HTTP pipeline context. * @param tokenRequestContext the token request context to be used for token acquisition. * @return a {@link Mono} containing {@link Void} */ public Mono<Void> setAuthorizationHeader(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { return setAuthorizationHeaderHelper(context, tokenRequestContext, true); } private Mono<Void> setAuthorizationHeaderHelper(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext, boolean checkToForceFetchToken) { return cache.getToken(tokenRequestContext, checkToForceFetchToken) .flatMap(token -> { context.getHttpRequest().getHeaders().set(AUTHORIZATION_HEADER, BEARER + " " + token.getToken()); return Mono.empty(); }); } }
class BearerTokenAuthenticationPolicy implements HttpPipelinePolicy { private static final String AUTHORIZATION_HEADER = "Authorization"; private static final String BEARER = "Bearer"; private final String[] scopes; private final AccessTokenCache cache; /** * Creates BearerTokenAuthenticationPolicy. * * @param credential the token credential to authenticate the request * @param scopes the scopes of authentication the credential should get token for */ public BearerTokenAuthenticationPolicy(TokenCredential credential, String... scopes) { Objects.requireNonNull(credential); this.scopes = scopes; this.cache = new AccessTokenCache(credential); } /** * Executed before sending the initial request and authenticates the request. * * @param context The request context. * @return A {@link Mono} containing {@link Void} */ public Mono<Void> authorizeRequest(HttpPipelineCallContext context) { if (this.scopes == null) { return Mono.empty(); } return setAuthorizationHeaderHelper(context, new TokenRequestContext().addScopes(this.scopes), false); } /** * Handles the authentication challenge in the event a 401 response with a WWW-Authenticate authentication * challenge header is received after the initial request and returns appropriate {@link TokenRequestContext} to * be used for re-authentication. * * @param context The request context. * @param response The Http Response containing the authentication challenge header. * @return A {@link Mono} containing {@link TokenRequestContext} */ public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { return Mono.just(false); } @Override /** * Authorizes the request with the bearer token acquired using the specified {@code tokenRequestContext} * * @param context the HTTP pipeline context. * @param tokenRequestContext the token request context to be used for token acquisition. * @return a {@link Mono} containing {@link Void} */ public Mono<Void> setAuthorizationHeader(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { return setAuthorizationHeaderHelper(context, tokenRequestContext, true); } private Mono<Void> setAuthorizationHeaderHelper(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext, boolean checkToForceFetchToken) { return cache.getToken(tokenRequestContext, checkToForceFetchToken) .flatMap(token -> { context.getHttpRequest().getHeaders().set(AUTHORIZATION_HEADER, BEARER + " " + token.getToken()); return Mono.empty(); }); } }
Assuming every model needs to write this, is there a way to do it before model's fromJson is called in a central place?
public static ResponseInnerError fromJson(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } ResponseInnerError innerError = new ResponseInnerError(); while ((token = jsonReader.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); if ("code".equals(fieldName)) { jsonReader.nextToken(); innerError.setCode(jsonReader.getStringValue()); } else if ("innererror".equals(fieldName)) { token = jsonReader.nextToken(); if (token != JsonToken.NULL) { innerError.setInnerError(ResponseInnerError.fromJson(jsonReader)); } } } return innerError; }
}
public static ResponseInnerError fromJson(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } ResponseInnerError innerError = new ResponseInnerError(); while ((token = jsonReader.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); if ("code".equals(fieldName)) { jsonReader.nextToken(); innerError.setCode(jsonReader.getStringValue()); } else if ("innererror".equals(fieldName)) { token = jsonReader.nextToken(); if (token != JsonToken.NULL) { innerError.setInnerError(ResponseInnerError.fromJson(jsonReader)); } } } return innerError; }
class ResponseInnerError implements JsonCapable<ResponseInnerError> { @JsonProperty(value = "code") private String code; @JsonProperty(value = "innererror") private ResponseInnerError innerError; /** * Returns the error code of the inner error. * * @return the error code of this inner error. */ public String getCode() { return code; } /** * Sets the error code of the inner error. * * @param code the error code of this inner error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setCode(String code) { this.code = code; return this; } /** * Returns the nested inner error for this error. * * @return the nested inner error for this error. */ public ResponseInnerError getInnerError() { return innerError; } /** * Sets the nested inner error for this error. * * @param innerError the nested inner error for this error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setInnerError(ResponseInnerError innerError) { this.innerError = innerError; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); jsonWriter.writeStringField("code", code) .writeFieldName("innererror"); if (innerError != null) { innerError.toJson(jsonWriter); } else { jsonWriter.writeNull(); } return jsonWriter.writeEndObject() .flush(); } /** * Creates an instance of {@link ResponseInnerError} by reading the {@link JsonReader}. * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link ResponseInnerError} if the {@link JsonReader} is pointing to * {@link ResponseInnerError} JSON content, or null if it is pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to the correct {@link JsonToken} when * passed. */ }
class ResponseInnerError implements JsonCapable<ResponseInnerError> { @JsonProperty(value = "code") private String code; @JsonProperty(value = "innererror") private ResponseInnerError innerError; /** * Returns the error code of the inner error. * * @return the error code of this inner error. */ public String getCode() { return code; } /** * Sets the error code of the inner error. * * @param code the error code of this inner error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setCode(String code) { this.code = code; return this; } /** * Returns the nested inner error for this error. * * @return the nested inner error for this error. */ public ResponseInnerError getInnerError() { return innerError; } /** * Sets the nested inner error for this error. * * @param innerError the nested inner error for this error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setInnerError(ResponseInnerError innerError) { this.innerError = innerError; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); jsonWriter.writeStringField("code", code) .writeFieldName("innererror"); if (innerError != null) { innerError.toJson(jsonWriter); } else { jsonWriter.writeNull(); } return jsonWriter.writeEndObject() .flush(); } /** * Creates an instance of {@link ResponseInnerError} by reading the {@link JsonReader}. * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link ResponseInnerError} if the {@link JsonReader} is pointing to * {@link ResponseInnerError} JSON content, or null if it is pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to the correct {@link JsonToken} when * passed. */ }
should we add some verbose logging?
public static ResponseInnerError fromJson(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } ResponseInnerError innerError = new ResponseInnerError(); while ((token = jsonReader.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); if ("code".equals(fieldName)) { jsonReader.nextToken(); innerError.setCode(jsonReader.getStringValue()); } else if ("innererror".equals(fieldName)) { token = jsonReader.nextToken(); if (token != JsonToken.NULL) { innerError.setInnerError(ResponseInnerError.fromJson(jsonReader)); } } } return innerError; }
public static ResponseInnerError fromJson(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } ResponseInnerError innerError = new ResponseInnerError(); while ((token = jsonReader.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); if ("code".equals(fieldName)) { jsonReader.nextToken(); innerError.setCode(jsonReader.getStringValue()); } else if ("innererror".equals(fieldName)) { token = jsonReader.nextToken(); if (token != JsonToken.NULL) { innerError.setInnerError(ResponseInnerError.fromJson(jsonReader)); } } } return innerError; }
class ResponseInnerError implements JsonCapable<ResponseInnerError> { @JsonProperty(value = "code") private String code; @JsonProperty(value = "innererror") private ResponseInnerError innerError; /** * Returns the error code of the inner error. * * @return the error code of this inner error. */ public String getCode() { return code; } /** * Sets the error code of the inner error. * * @param code the error code of this inner error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setCode(String code) { this.code = code; return this; } /** * Returns the nested inner error for this error. * * @return the nested inner error for this error. */ public ResponseInnerError getInnerError() { return innerError; } /** * Sets the nested inner error for this error. * * @param innerError the nested inner error for this error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setInnerError(ResponseInnerError innerError) { this.innerError = innerError; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); jsonWriter.writeStringField("code", code) .writeFieldName("innererror"); if (innerError != null) { innerError.toJson(jsonWriter); } else { jsonWriter.writeNull(); } return jsonWriter.writeEndObject() .flush(); } /** * Creates an instance of {@link ResponseInnerError} by reading the {@link JsonReader}. * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link ResponseInnerError} if the {@link JsonReader} is pointing to * {@link ResponseInnerError} JSON content, or null if it is pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to the correct {@link JsonToken} when * passed. */ }
class ResponseInnerError implements JsonCapable<ResponseInnerError> { @JsonProperty(value = "code") private String code; @JsonProperty(value = "innererror") private ResponseInnerError innerError; /** * Returns the error code of the inner error. * * @return the error code of this inner error. */ public String getCode() { return code; } /** * Sets the error code of the inner error. * * @param code the error code of this inner error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setCode(String code) { this.code = code; return this; } /** * Returns the nested inner error for this error. * * @return the nested inner error for this error. */ public ResponseInnerError getInnerError() { return innerError; } /** * Sets the nested inner error for this error. * * @param innerError the nested inner error for this error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setInnerError(ResponseInnerError innerError) { this.innerError = innerError; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); jsonWriter.writeStringField("code", code) .writeFieldName("innererror"); if (innerError != null) { innerError.toJson(jsonWriter); } else { jsonWriter.writeNull(); } return jsonWriter.writeEndObject() .flush(); } /** * Creates an instance of {@link ResponseInnerError} by reading the {@link JsonReader}. * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link ResponseInnerError} if the {@link JsonReader} is pointing to * {@link ResponseInnerError} JSON content, or null if it is pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to the correct {@link JsonToken} when * passed. */ }
I'd rather leave this to the model as there could be cases where `JsonToken.NULL` results in a default value being returned. And, centralizing this would make any one-off behaviors needed much harder to integrate. I'm not as worried on duplicating this as an overwhelming majority of implementations will be code generated.
public static ResponseInnerError fromJson(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } ResponseInnerError innerError = new ResponseInnerError(); while ((token = jsonReader.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); if ("code".equals(fieldName)) { jsonReader.nextToken(); innerError.setCode(jsonReader.getStringValue()); } else if ("innererror".equals(fieldName)) { token = jsonReader.nextToken(); if (token != JsonToken.NULL) { innerError.setInnerError(ResponseInnerError.fromJson(jsonReader)); } } } return innerError; }
}
public static ResponseInnerError fromJson(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } ResponseInnerError innerError = new ResponseInnerError(); while ((token = jsonReader.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); if ("code".equals(fieldName)) { jsonReader.nextToken(); innerError.setCode(jsonReader.getStringValue()); } else if ("innererror".equals(fieldName)) { token = jsonReader.nextToken(); if (token != JsonToken.NULL) { innerError.setInnerError(ResponseInnerError.fromJson(jsonReader)); } } } return innerError; }
class ResponseInnerError implements JsonCapable<ResponseInnerError> { @JsonProperty(value = "code") private String code; @JsonProperty(value = "innererror") private ResponseInnerError innerError; /** * Returns the error code of the inner error. * * @return the error code of this inner error. */ public String getCode() { return code; } /** * Sets the error code of the inner error. * * @param code the error code of this inner error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setCode(String code) { this.code = code; return this; } /** * Returns the nested inner error for this error. * * @return the nested inner error for this error. */ public ResponseInnerError getInnerError() { return innerError; } /** * Sets the nested inner error for this error. * * @param innerError the nested inner error for this error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setInnerError(ResponseInnerError innerError) { this.innerError = innerError; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); jsonWriter.writeStringField("code", code) .writeFieldName("innererror"); if (innerError != null) { innerError.toJson(jsonWriter); } else { jsonWriter.writeNull(); } return jsonWriter.writeEndObject() .flush(); } /** * Creates an instance of {@link ResponseInnerError} by reading the {@link JsonReader}. * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link ResponseInnerError} if the {@link JsonReader} is pointing to * {@link ResponseInnerError} JSON content, or null if it is pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to the correct {@link JsonToken} when * passed. */ }
class ResponseInnerError implements JsonCapable<ResponseInnerError> { @JsonProperty(value = "code") private String code; @JsonProperty(value = "innererror") private ResponseInnerError innerError; /** * Returns the error code of the inner error. * * @return the error code of this inner error. */ public String getCode() { return code; } /** * Sets the error code of the inner error. * * @param code the error code of this inner error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setCode(String code) { this.code = code; return this; } /** * Returns the nested inner error for this error. * * @return the nested inner error for this error. */ public ResponseInnerError getInnerError() { return innerError; } /** * Sets the nested inner error for this error. * * @param innerError the nested inner error for this error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setInnerError(ResponseInnerError innerError) { this.innerError = innerError; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); jsonWriter.writeStringField("code", code) .writeFieldName("innererror"); if (innerError != null) { innerError.toJson(jsonWriter); } else { jsonWriter.writeNull(); } return jsonWriter.writeEndObject() .flush(); } /** * Creates an instance of {@link ResponseInnerError} by reading the {@link JsonReader}. * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link ResponseInnerError} if the {@link JsonReader} is pointing to * {@link ResponseInnerError} JSON content, or null if it is pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to the correct {@link JsonToken} when * passed. */ }
Good idea, I'll add that once the implementation finalizes further.
public static ResponseInnerError fromJson(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } ResponseInnerError innerError = new ResponseInnerError(); while ((token = jsonReader.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); if ("code".equals(fieldName)) { jsonReader.nextToken(); innerError.setCode(jsonReader.getStringValue()); } else if ("innererror".equals(fieldName)) { token = jsonReader.nextToken(); if (token != JsonToken.NULL) { innerError.setInnerError(ResponseInnerError.fromJson(jsonReader)); } } } return innerError; }
public static ResponseInnerError fromJson(JsonReader jsonReader) { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); } if (token == JsonToken.NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new IllegalStateException("Unexpected token to begin deserialization: " + token); } ResponseInnerError innerError = new ResponseInnerError(); while ((token = jsonReader.nextToken()) != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); if ("code".equals(fieldName)) { jsonReader.nextToken(); innerError.setCode(jsonReader.getStringValue()); } else if ("innererror".equals(fieldName)) { token = jsonReader.nextToken(); if (token != JsonToken.NULL) { innerError.setInnerError(ResponseInnerError.fromJson(jsonReader)); } } } return innerError; }
class ResponseInnerError implements JsonCapable<ResponseInnerError> { @JsonProperty(value = "code") private String code; @JsonProperty(value = "innererror") private ResponseInnerError innerError; /** * Returns the error code of the inner error. * * @return the error code of this inner error. */ public String getCode() { return code; } /** * Sets the error code of the inner error. * * @param code the error code of this inner error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setCode(String code) { this.code = code; return this; } /** * Returns the nested inner error for this error. * * @return the nested inner error for this error. */ public ResponseInnerError getInnerError() { return innerError; } /** * Sets the nested inner error for this error. * * @param innerError the nested inner error for this error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setInnerError(ResponseInnerError innerError) { this.innerError = innerError; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); jsonWriter.writeStringField("code", code) .writeFieldName("innererror"); if (innerError != null) { innerError.toJson(jsonWriter); } else { jsonWriter.writeNull(); } return jsonWriter.writeEndObject() .flush(); } /** * Creates an instance of {@link ResponseInnerError} by reading the {@link JsonReader}. * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link ResponseInnerError} if the {@link JsonReader} is pointing to * {@link ResponseInnerError} JSON content, or null if it is pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to the correct {@link JsonToken} when * passed. */ }
class ResponseInnerError implements JsonCapable<ResponseInnerError> { @JsonProperty(value = "code") private String code; @JsonProperty(value = "innererror") private ResponseInnerError innerError; /** * Returns the error code of the inner error. * * @return the error code of this inner error. */ public String getCode() { return code; } /** * Sets the error code of the inner error. * * @param code the error code of this inner error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setCode(String code) { this.code = code; return this; } /** * Returns the nested inner error for this error. * * @return the nested inner error for this error. */ public ResponseInnerError getInnerError() { return innerError; } /** * Sets the nested inner error for this error. * * @param innerError the nested inner error for this error. * @return the updated {@link ResponseInnerError} instance. */ public ResponseInnerError setInnerError(ResponseInnerError innerError) { this.innerError = innerError; return this; } @Override public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject(); jsonWriter.writeStringField("code", code) .writeFieldName("innererror"); if (innerError != null) { innerError.toJson(jsonWriter); } else { jsonWriter.writeNull(); } return jsonWriter.writeEndObject() .flush(); } /** * Creates an instance of {@link ResponseInnerError} by reading the {@link JsonReader}. * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link ResponseInnerError} if the {@link JsonReader} is pointing to * {@link ResponseInnerError} JSON content, or null if it is pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to the correct {@link JsonToken} when * passed. */ }
```suggestion * @param customerProvidedKey the {@link CustomerProvidedKey} for the path, ```
public DataLakePathAsyncClient getCustomerProvidedKeyAsyncClient(CustomerProvidedKey customerProvidedKey) { CpkInfo finalCustomerProvidedKey = null; if (customerProvidedKey != null) { finalCustomerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return new DataLakePathAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getFileSystemName(), getObjectPath(), this.pathResourceType, this.blockBlobAsyncClient, finalCustomerProvidedKey); }
.setEncryptionKey(customerProvidedKey.getKey())
public DataLakePathAsyncClient getCustomerProvidedKeyAsyncClient(CustomerProvidedKey customerProvidedKey) { CpkInfo finalCustomerProvidedKey = null; if (customerProvidedKey != null) { finalCustomerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return new DataLakePathAsyncClient(getHttpPipeline(), getAccountUrl(), getServiceVersion(), getAccountName(), getFileSystemName(), getObjectPath(), this.pathResourceType, this.blockBlobAsyncClient, getSasToken(), finalCustomerProvidedKey); }
class DataLakePathAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(DataLakePathAsyncClient.class); final AzureDataLakeStorageRestAPIImpl dataLakeStorage; final AzureDataLakeStorageRestAPIImpl fileSystemDataLakeStorage; /** * This {@link AzureDataLakeStorageRestAPIImpl} is pointing to blob endpoint instead of dfs * in order to expose APIs that are on blob endpoint but are only functional for HNS enabled accounts. */ final AzureDataLakeStorageRestAPIImpl blobDataLakeStorage; private final String accountName; private final String fileSystemName; final String pathName; private final DataLakeServiceVersion serviceVersion; private final CpkInfo customerProvidedKey; final PathResourceType pathResourceType; final BlockBlobAsyncClient blockBlobAsyncClient; /** * Package-private constructor for use by {@link DataLakePathClientBuilder}. * * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param fileSystemName The file system name. * @param pathName The path name. * @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient} */ DataLakePathAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion, String accountName, String fileSystemName, String pathName, PathResourceType pathResourceType, BlockBlobAsyncClient blockBlobAsyncClient, CpkInfo customerProvidedKey) { this.accountName = accountName; this.fileSystemName = fileSystemName; this.pathName = Utility.urlDecode(pathName); this.pathResourceType = pathResourceType; this.blockBlobAsyncClient = blockBlobAsyncClient; this.dataLakeStorage = new AzureDataLakeStorageRestAPIImplBuilder() .pipeline(pipeline) .url(url) .fileSystem(fileSystemName) .path(this.pathName) .version(serviceVersion.getVersion()) .buildClient(); this.serviceVersion = serviceVersion; String blobUrl = DataLakeImplUtils.endpointToDesiredEndpoint(url, "blob", "dfs"); this.blobDataLakeStorage = new AzureDataLakeStorageRestAPIImplBuilder() .pipeline(pipeline) .url(blobUrl) .fileSystem(fileSystemName) .path(this.pathName) .version(serviceVersion.getVersion()) .buildClient(); this.fileSystemDataLakeStorage = new AzureDataLakeStorageRestAPIImplBuilder() .pipeline(pipeline) .url(url) .fileSystem(fileSystemName) .version(serviceVersion.getVersion()) .buildClient(); this.customerProvidedKey = customerProvidedKey; } /** * Converts the metadata into a string of format "key1=value1, key2=value2" and Base64 encodes the values. * * @param metadata The metadata. * * @return The metadata represented as a String. */ static String buildMetadataString(Map<String, String> metadata) { if (!CoreUtils.isNullOrEmpty(metadata)) { StringBuilder sb = new StringBuilder(); for (final Map.Entry<String, String> entry : metadata.entrySet()) { if (Objects.isNull(entry.getKey()) || entry.getKey().isEmpty()) { throw new IllegalArgumentException("The key for one of the metadata key-value pairs is null, " + "empty, or whitespace."); } else if (Objects.isNull(entry.getValue()) || entry.getValue().isEmpty()) { throw new IllegalArgumentException("The value for one of the metadata key-value pairs is null, " + "empty, or whitespace."); } /* The service has an internal base64 decode when metadata is copied from ADLS to Storage, so getMetadata will work as normal. Doing this encoding for the customers preserves the existing behavior of metadata. */ sb.append(entry.getKey()).append('=') .append(new String(Base64.getEncoder().encode(entry.getValue().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8)).append(','); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } else { return null; } } /** * Gets the URL of the storage account. * * @return the URL. */ String getAccountUrl() { return dataLakeStorage.getUrl(); } /** * Gets the URL of the object represented by this client on the Data Lake service. * * @return the URL. */ String getPathUrl() { return dataLakeStorage.getUrl() + "/" + fileSystemName + "/" + Utility.urlEncode(pathName); } /** * Gets the associated account name. * * @return Account name associated with this storage resource. */ public String getAccountName() { return accountName; } /** * Gets the name of the File System in which this object lives. * * @return The name of the File System. */ public String getFileSystemName() { return fileSystemName; } /** * Gets the full path of this object. * * @return The path of the object. */ String getObjectPath() { return pathName; } /** * Gets the name of this object, not including its full path. * * @return The name of the object. */ String getObjectName() { String[] pathParts = getObjectPath().split("/"); return pathParts[pathParts.length - 1]; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return dataLakeStorage.getHttpPipeline(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public DataLakeServiceVersion getServiceVersion() { return serviceVersion; } /** * Gets the {@link CpkInfo} used to encrypt this path's content on the server. * * @return the customer provided key used for encryption. */ public CustomerProvidedKey getCustomerProvidedKey() { return new CustomerProvidedKey(customerProvidedKey.getEncryptionKey()); } CpkInfo getCpkInfo() { return this.customerProvidedKey; } /** * Creates a new {@link DataLakePathAsyncClient} with the specified {@code customerProvidedKey}. * * @param customerProvidedKey the {@link CustomerProvidedKey} for the blob, * pass {@code null} to use no customer provided key. * @return a {@link DataLakePathAsyncClient} with the specified {@code customerProvidedKey}. */ /** * Creates a resource. By default, this method will not overwrite an existing path. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.create --> * <pre> * client.create& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.create --> * * <p>For more information see the * <a href="https: * Docs</a></p> * * @return A reactive response containing information about the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> create() { return create(false); } /** * Creates a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.create * <pre> * boolean overwrite = true; * client.create& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.create * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param overwrite Whether to overwrite, should data exist on the file. * * @return A reactive response containing information about the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> create(boolean overwrite) { DataLakeRequestConditions requestConditions = new DataLakeRequestConditions(); if (!overwrite) { requestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return createWithResponse(null, null, null, null, requestConditions).flatMap(FluxUtil::toMono); } /** * Creates a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.createWithResponse * <pre> * PathHttpHeaders httpHeaders = new PathHttpHeaders& * .setContentLanguage& * .setContentType& * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * .setLeaseId& * String permissions = &quot;permissions&quot;; * String umask = &quot;umask&quot;; * * client.createWithResponse& * requestConditions& * .subscribe& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.createWithResponse * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param permissions POSIX access permissions for the resource owner, the resource owning group, and others. * @param umask Restricts permissions of the resource to be created. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return A {@link Mono} containing a {@link Response} whose {@link Response * PathItem}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> createWithResponse(String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { try { return withContext(context -> createWithResponse(permissions, umask, pathResourceType, headers, metadata, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<PathInfo>> createWithResponse(String permissions, String umask, PathResourceType resourceType, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions, Context context) { requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().createWithResponseAsync(null, null, resourceType, null, null, null, null, buildMetadataString(metadata), permissions, umask, headers, lac, mac, null, customerProvidedKey, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathInfo(response.getDeserializedHeaders().getETag(), response.getDeserializedHeaders().getLastModified(), response.getDeserializedHeaders().isXMsRequestServerEncrypted() != null, response.getDeserializedHeaders().getXMsEncryptionKeySha256()))); } /** * Package-private delete method for use by {@link DataLakeFileAsyncClient} and {@link DataLakeDirectoryAsyncClient} * * @param recursive Whether to delete all paths beneath the directory. * @param requestConditions {@link DataLakeRequestConditions} * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Mono} containing status code and HTTP headers */ Mono<Response<Void>> deleteWithResponse(Boolean recursive, DataLakeRequestConditions requestConditions, Context context) { requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().deleteWithResponseAsync(null, null, recursive, null, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, null)); } /** * Changes a resource's metadata. The specified metadata in this method will replace existing metadata. If old * values must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setMetadata * <pre> * client.setMetadata& * .subscribe& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono); } /** * Changes a resource's metadata. The specified metadata in this method will replace existing metadata. If old * values must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setMetadata * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * * client.setMetadataWithResponse& * .subscribe& * response.getStatusCode& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, DataLakeRequestConditions requestConditions) { return this.blockBlobAsyncClient.setMetadataWithResponse(metadata, Transforms.toBlobRequestConditions(requestConditions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Changes a resource's HTTP header properties. If only one HTTP header is updated, the others will all be erased. * In order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setHttpHeaders * <pre> * client.setHttpHeaders& * .setContentLanguage& * .setContentType& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setHttpHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link PathHttpHeaders} * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setHttpHeaders(PathHttpHeaders headers) { return setHttpHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono); } /** * Changes a resource's HTTP header properties. If only one HTTP header is updated, the others will all be erased. * In order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setHttpHeadersWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * * client.setHttpHeadersWithResponse& * .setContentLanguage& * .setContentType& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setHttpHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link PathHttpHeaders} * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setHttpHeadersWithResponse(PathHttpHeaders headers, DataLakeRequestConditions requestConditions) { return this.blockBlobAsyncClient.setHttpHeadersWithResponse(Transforms.toBlobHttpHeaders(headers), Transforms.toBlobRequestConditions(requestConditions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Returns the resource's metadata and properties. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.getProperties --> * <pre> * client.getProperties& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.getProperties --> * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the resource's properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> getProperties() { return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono); } /** * Returns the resource's metadata and properties. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.getPropertiesWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * * client.getPropertiesWithResponse& * response -&gt; System.out.printf& * response.getValue& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the resource's properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathProperties>> getPropertiesWithResponse(DataLakeRequestConditions requestConditions) { return blockBlobAsyncClient.getPropertiesWithResponse(Transforms.toBlobRequestConditions(requestConditions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException) .map(response -> new SimpleResponse<>(response, Transforms.toPathProperties(response.getValue()))); } /** * Determines if the path this client represents exists in the cloud. * <p>Note that this method does not guarantee that the path type (file/directory) matches expectations.</p> * <p>For example, a DataLakeFileClient representing a path to a datalake directory will return true, and vice * versa.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.exists --> * <pre> * client.exists& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.exists --> * * @return true if the path exists, false if it doesn't */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> exists() { return existsWithResponse().flatMap(FluxUtil::toMono); } /** * Determines if the path this client represents exists in the cloud. * <p>Note that this method does not guarantee that the path type (file/directory) matches expectations.</p> * <p>For example, a DataLakeFileClient representing a path to a datalake directory will return true, and vice * versa.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.existsWithResponse --> * <pre> * client.existsWithResponse& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.existsWithResponse --> * * @return true if the path exists, false if it doesn't */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> existsWithResponse() { return blockBlobAsyncClient.existsWithResponse().onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Changes the access control list, group and/or owner for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlList * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * String group = &quot;group&quot;; * String owner = &quot;owner&quot;; * * client.setAccessControlList& * response -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlList * * <p>For more information, see the * <a href="https: * * @param accessControlList A list of {@link PathAccessControlEntry} objects. * @param group The group of the resource. * @param owner The owner of the resource. * @return A reactive response containing the resource info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> setAccessControlList(List<PathAccessControlEntry> accessControlList, String group, String owner) { return setAccessControlListWithResponse(accessControlList, group, owner, null).flatMap(FluxUtil::toMono); } /** * Changes the access control list, group and/or owner for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlListWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * String group = &quot;group&quot;; * String owner = &quot;owner&quot;; * * client.setAccessControlListWithResponse& * response -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlListWithResponse * * <p>For more information, see the * <a href="https: * * @param accessControlList A list of {@link PathAccessControlEntry} objects. * @param group The group of the resource. * @param owner The owner of the resource. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the resource info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> setAccessControlListWithResponse(List<PathAccessControlEntry> accessControlList, String group, String owner, DataLakeRequestConditions requestConditions) { try { return withContext(context -> setAccessControlWithResponse(accessControlList, null, group, owner, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } /** * Changes the permissions, group and/or owner for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setPermissions * <pre> * PathPermissions permissions = new PathPermissions& * .setGroup& * .setOwner& * .setOther& * String group = &quot;group&quot;; * String owner = &quot;owner&quot;; * * client.setPermissions& * response -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setPermissions * * <p>For more information, see the * <a href="https: * * @param permissions {@link PathPermissions} * @param group The group of the resource. * @param owner The owner of the resource. * @return A reactive response containing the resource info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> setPermissions(PathPermissions permissions, String group, String owner) { return setPermissionsWithResponse(permissions, group, owner, null).flatMap(FluxUtil::toMono); } /** * Changes the permissions, group and/or owner for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setPermissionsWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * PathPermissions permissions = new PathPermissions& * .setGroup& * .setOwner& * .setOther& * String group = &quot;group&quot;; * String owner = &quot;owner&quot;; * * client.setPermissionsWithResponse& * response -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setPermissionsWithResponse * * <p>For more information, see the * <a href="https: * * @param permissions {@link PathPermissions} * @param group The group of the resource. * @param owner The owner of the resource. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the resource info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> setPermissionsWithResponse(PathPermissions permissions, String group, String owner, DataLakeRequestConditions requestConditions) { try { return withContext(context -> setAccessControlWithResponse(null, permissions, group, owner, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<PathInfo>> setAccessControlWithResponse(List<PathAccessControlEntry> accessControlList, PathPermissions permissions, String group, String owner, DataLakeRequestConditions requestConditions, Context context) { requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); String permissionsString = permissions == null ? null : permissions.toString(); String accessControlListString = accessControlList == null ? null : PathAccessControlEntry.serializeList(accessControlList); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().setAccessControlWithResponseAsync(null, owner, group, permissionsString, accessControlListString, null, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathInfo(response.getDeserializedHeaders().getETag(), response.getDeserializedHeaders().getLastModified()))); } /** * Recursively sets the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlRecursive * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * client.setAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlRecursive * * <p>For more information, see the * <a href="https: * * @param accessControlList The POSIX access control list for the file or directory. * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AccessControlChangeResult> setAccessControlRecursive(List<PathAccessControlEntry> accessControlList) { return setAccessControlRecursiveWithResponse(new PathSetAccessControlRecursiveOptions(accessControlList)) .flatMap(FluxUtil::toMono); } /** * Recursively sets the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlRecursiveWithResponse * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * Integer batchSize = 2; * Integer maxBatches = 10; * boolean continueOnFailure = false; * String continuationToken = null; * Consumer&lt;Response&lt;AccessControlChanges&gt;&gt; progressHandler = * response -&gt; System.out.println& * * PathSetAccessControlRecursiveOptions options = * new PathSetAccessControlRecursiveOptions& * .setBatchSize& * .setMaxBatches& * .setContinueOnFailure& * .setContinuationToken& * .setProgressHandler& * * client.setAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlRecursiveWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link PathSetAccessControlRecursiveOptions} * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AccessControlChangeResult>> setAccessControlRecursiveWithResponse( PathSetAccessControlRecursiveOptions options) { try { StorageImplUtils.assertNotNull("options", options); return withContext(context -> setAccessControlRecursiveWithResponse( PathAccessControlEntry.serializeList(options.getAccessControlList()), options.getProgressHandler(), PathSetAccessControlRecursiveMode.SET, options.getBatchSize(), options.getMaxBatches(), options.isContinueOnFailure(), options.getContinuationToken(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } /** * Recursively updates the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.updateAccessControlRecursive * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * client.updateAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.updateAccessControlRecursive * * <p>For more information, see the * <a href="https: * * @param accessControlList The POSIX access control list for the file or directory. * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AccessControlChangeResult> updateAccessControlRecursive( List<PathAccessControlEntry> accessControlList) { return updateAccessControlRecursiveWithResponse(new PathUpdateAccessControlRecursiveOptions(accessControlList)) .flatMap(FluxUtil::toMono); } /** * Recursively updates the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.updateAccessControlRecursiveWithResponse * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * Integer batchSize = 2; * Integer maxBatches = 10; * boolean continueOnFailure = false; * String continuationToken = null; * Consumer&lt;Response&lt;AccessControlChanges&gt;&gt; progressHandler = * response -&gt; System.out.println& * * PathUpdateAccessControlRecursiveOptions options = * new PathUpdateAccessControlRecursiveOptions& * .setBatchSize& * .setMaxBatches& * .setContinueOnFailure& * .setContinuationToken& * .setProgressHandler& * * client.updateAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.updateAccessControlRecursiveWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link PathUpdateAccessControlRecursiveOptions} * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AccessControlChangeResult>> updateAccessControlRecursiveWithResponse( PathUpdateAccessControlRecursiveOptions options) { try { StorageImplUtils.assertNotNull("options", options); return withContext(context -> setAccessControlRecursiveWithResponse( PathAccessControlEntry.serializeList(options.getAccessControlList()), options.getProgressHandler(), PathSetAccessControlRecursiveMode.MODIFY, options.getBatchSize(), options.getMaxBatches(), options.isContinueOnFailure(), options.getContinuationToken(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } /** * Recursively removes the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.removeAccessControlRecursive * <pre> * PathRemoveAccessControlEntry pathAccessControlEntry = new PathRemoveAccessControlEntry& * .setEntityId& * List&lt;PathRemoveAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * client.removeAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.removeAccessControlRecursive * * <p>For more information, see the * <a href="https: * * @param accessControlList The POSIX access control list for the file or directory. * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AccessControlChangeResult> removeAccessControlRecursive( List<PathRemoveAccessControlEntry> accessControlList) { return removeAccessControlRecursiveWithResponse(new PathRemoveAccessControlRecursiveOptions(accessControlList)) .flatMap(FluxUtil::toMono); } /** * Recursively removes the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.removeAccessControlRecursiveWithResponse * <pre> * PathRemoveAccessControlEntry pathAccessControlEntry = new PathRemoveAccessControlEntry& * .setEntityId& * List&lt;PathRemoveAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * Integer batchSize = 2; * Integer maxBatches = 10; * boolean continueOnFailure = false; * String continuationToken = null; * Consumer&lt;Response&lt;AccessControlChanges&gt;&gt; progressHandler = * response -&gt; System.out.println& * * PathRemoveAccessControlRecursiveOptions options = * new PathRemoveAccessControlRecursiveOptions& * .setBatchSize& * .setMaxBatches& * .setContinueOnFailure& * .setContinuationToken& * .setProgressHandler& * * client.removeAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.removeAccessControlRecursiveWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link PathRemoveAccessControlRecursiveOptions} * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AccessControlChangeResult>> removeAccessControlRecursiveWithResponse( PathRemoveAccessControlRecursiveOptions options) { try { StorageImplUtils.assertNotNull("options", options); return withContext(context -> setAccessControlRecursiveWithResponse( PathRemoveAccessControlEntry.serializeList(options.getAccessControlList()), options.getProgressHandler(), PathSetAccessControlRecursiveMode.REMOVE, options.getBatchSize(), options.getMaxBatches(), options.isContinueOnFailure(), options.getContinuationToken(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<AccessControlChangeResult>> setAccessControlRecursiveWithResponse( String accessControlList, Consumer<Response<AccessControlChanges>> progressHandler, PathSetAccessControlRecursiveMode mode, Integer batchSize, Integer maxBatches, Boolean continueOnFailure, String continuationToken, Context context) { StorageImplUtils.assertNotNull("accessControlList", accessControlList); context = context == null ? Context.NONE : context; Context contextFinal = context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE); AtomicInteger directoriesSuccessfulCount = new AtomicInteger(0); AtomicInteger filesSuccessfulCount = new AtomicInteger(0); AtomicInteger failureCount = new AtomicInteger(0); AtomicInteger batchesCount = new AtomicInteger(0); return this.dataLakeStorage.getPaths().setAccessControlRecursiveWithResponseAsync(mode, null, continuationToken, continueOnFailure, batchSize, accessControlList, null, contextFinal) .onErrorMap(e -> { if (e instanceof DataLakeStorageException) { return LOGGER.logExceptionAsError(ModelHelper.changeAclRequestFailed((DataLakeStorageException) e, continuationToken)); } else if (e instanceof Exception) { return LOGGER.logExceptionAsError(ModelHelper.changeAclFailed((Exception) e, continuationToken)); } return e; }) .flatMap(response -> setAccessControlRecursiveWithResponseHelper(response, maxBatches, directoriesSuccessfulCount, filesSuccessfulCount, failureCount, batchesCount, progressHandler, accessControlList, mode, batchSize, continueOnFailure, continuationToken, null, contextFinal)); } Mono<Response<AccessControlChangeResult>> setAccessControlRecursiveWithResponseHelper( PathsSetAccessControlRecursiveResponse response, Integer maxBatches, AtomicInteger directoriesSuccessfulCount, AtomicInteger filesSuccessfulCount, AtomicInteger failureCount, AtomicInteger batchesCount, Consumer<Response<AccessControlChanges>> progressHandler, String accessControlStr, PathSetAccessControlRecursiveMode mode, Integer batchSize, Boolean continueOnFailure, String lastToken, List<AccessControlChangeFailure> batchFailures, Context context) { batchesCount.incrementAndGet(); directoriesSuccessfulCount.addAndGet(response.getValue().getDirectoriesSuccessful()); filesSuccessfulCount.addAndGet(response.getValue().getFilesSuccessful()); failureCount.addAndGet(response.getValue().getFailureCount()); if (failureCount.get() > 0 && batchFailures == null) { batchFailures = response.getValue().getFailedEntries() .stream() .map(aclFailedEntry -> new AccessControlChangeFailure() .setDirectory(aclFailedEntry.getType().equals("DIRECTORY")) .setName(aclFailedEntry.getName()) .setErrorMessage(aclFailedEntry.getErrorMessage()) ).collect(Collectors.toList()); } List<AccessControlChangeFailure> finalBatchFailures = batchFailures; /* Determine which token we should report/return/use next. If there was a token present on the response (still processing and either no errors or forceFlag set), use that one. If there were no failures or force flag set and still nothing present, we are at the end, so use that. If there were failures and no force flag set, use the last token (no token is returned in this case). */ String newToken = response.getDeserializedHeaders().getXMsContinuation(); String effectiveNextToken; if (newToken != null && !newToken.isEmpty()) { effectiveNextToken = newToken; } else { if (failureCount.get() == 0 || (continueOnFailure == null || continueOnFailure)) { effectiveNextToken = newToken; } else { effectiveNextToken = lastToken; } } if (progressHandler != null) { AccessControlChanges changes = new AccessControlChanges(); changes.setContinuationToken(effectiveNextToken); changes.setBatchFailures( response.getValue().getFailedEntries() .stream() .map(aclFailedEntry -> new AccessControlChangeFailure() .setDirectory(aclFailedEntry.getType().equals("DIRECTORY")) .setName(aclFailedEntry.getName()) .setErrorMessage(aclFailedEntry.getErrorMessage()) ).collect(Collectors.toList()) ); changes.setBatchCounters(new AccessControlChangeCounters() .setChangedDirectoriesCount(response.getValue().getDirectoriesSuccessful()) .setChangedFilesCount(response.getValue().getFilesSuccessful()) .setFailedChangesCount(response.getValue().getFailureCount())); changes.setAggregateCounters(new AccessControlChangeCounters() .setChangedDirectoriesCount(directoriesSuccessfulCount.get()) .setChangedFilesCount(filesSuccessfulCount.get()) .setFailedChangesCount(failureCount.get())); progressHandler.accept( new ResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), changes, response.getDeserializedHeaders())); } /* Determine if we are finished either because there is no new continuation (failure or finished) token or we have hit maxBatches. */ if ((newToken == null || newToken.isEmpty()) || (maxBatches != null && batchesCount.get() >= maxBatches)) { AccessControlChangeResult result = new AccessControlChangeResult() .setBatchFailures(batchFailures) .setContinuationToken(effectiveNextToken) .setCounters(new AccessControlChangeCounters() .setChangedDirectoriesCount(directoriesSuccessfulCount.get()) .setChangedFilesCount(filesSuccessfulCount.get()) .setFailedChangesCount(failureCount.get())); return Mono.just(new ResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result, response.getDeserializedHeaders() )); } return this.dataLakeStorage.getPaths().setAccessControlRecursiveWithResponseAsync(mode, null, effectiveNextToken, continueOnFailure, batchSize, accessControlStr, null, context) .onErrorMap(e -> { if (e instanceof DataLakeStorageException) { return LOGGER.logExceptionAsError(ModelHelper.changeAclRequestFailed((DataLakeStorageException) e, effectiveNextToken)); } else if (e instanceof Exception) { return LOGGER.logExceptionAsError(ModelHelper.changeAclFailed((Exception) e, effectiveNextToken)); } return e; }) .flatMap(response2 -> setAccessControlRecursiveWithResponseHelper(response2, maxBatches, directoriesSuccessfulCount, filesSuccessfulCount, failureCount, batchesCount, progressHandler, accessControlStr, mode, batchSize, continueOnFailure, effectiveNextToken, finalBatchFailures, context)); } /** * Returns the access control for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.getAccessControl --> * <pre> * client.getAccessControl& * response -&gt; System.out.printf& * PathAccessControlEntry.serializeList& * response.getOwner& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.getAccessControl --> * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the resource access control. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathAccessControl> getAccessControl() { return getAccessControlWithResponse(false, null).flatMap(FluxUtil::toMono); } /** * Returns the access control for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.getAccessControlWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * boolean userPrincipalNameReturned = false; * * client.getAccessControlWithResponse& * response -&gt; System.out.printf& * PathAccessControlEntry.serializeList& * response.getValue& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.getAccessControlWithResponse * * <p>For more information, see the * <a href="https: * * @param userPrincipalNameReturned When true, user identity values returned as User Principal Names. When false, * user identity values returned as Azure Active Directory Object IDs. Default value is false. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the resource access control. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathAccessControl>> getAccessControlWithResponse(boolean userPrincipalNameReturned, DataLakeRequestConditions requestConditions) { try { return withContext(context -> getAccessControlWithResponse(userPrincipalNameReturned, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<PathAccessControl>> getAccessControlWithResponse(boolean userPrincipalNameReturned, DataLakeRequestConditions requestConditions, Context context) { requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().getPropertiesWithResponseAsync(null, null, PathGetPropertiesAction.GET_ACCESS_CONTROL, userPrincipalNameReturned, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathAccessControl( PathAccessControlEntry.parseList(response.getDeserializedHeaders().getXMsAcl()), PathPermissions.parseSymbolic(response.getDeserializedHeaders().getXMsPermissions()), response.getDeserializedHeaders().getXMsGroup(), response.getDeserializedHeaders().getXMsOwner()))); } /** * Package-private rename method for use by {@link DataLakeFileAsyncClient} and {@link DataLakeDirectoryAsyncClient} * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath The path of the destination relative to the file system name * @param sourceRequestConditions {@link DataLakeRequestConditions} against the source. * @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DataLakePathAsyncClient} used to interact with the path created. */ Mono<Response<DataLakePathAsyncClient>> renameWithResponse(String destinationFileSystem, String destinationPath, DataLakeRequestConditions sourceRequestConditions, DataLakeRequestConditions destinationRequestConditions, Context context) { destinationRequestConditions = destinationRequestConditions == null ? new DataLakeRequestConditions() : destinationRequestConditions; sourceRequestConditions = sourceRequestConditions == null ? new DataLakeRequestConditions() : sourceRequestConditions; SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions() .setSourceIfModifiedSince(sourceRequestConditions.getIfModifiedSince()) .setSourceIfUnmodifiedSince(sourceRequestConditions.getIfUnmodifiedSince()) .setSourceIfMatch(sourceRequestConditions.getIfMatch()) .setSourceIfNoneMatch(sourceRequestConditions.getIfNoneMatch()); LeaseAccessConditions destLac = new LeaseAccessConditions() .setLeaseId(destinationRequestConditions.getLeaseId()); ModifiedAccessConditions destMac = new ModifiedAccessConditions() .setIfMatch(destinationRequestConditions.getIfMatch()) .setIfNoneMatch(destinationRequestConditions.getIfNoneMatch()) .setIfModifiedSince(destinationRequestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(destinationRequestConditions.getIfUnmodifiedSince()); DataLakePathAsyncClient dataLakePathAsyncClient = getPathAsyncClient(destinationFileSystem, destinationPath); String renameSource = "/" + this.fileSystemName + "/" + Utility.urlEncode(pathName); return dataLakePathAsyncClient.dataLakeStorage.getPaths().createWithResponseAsync( null /* request id */, null /* timeout */, null /* pathResourceType */, null /* continuation */, PathRenameMode.LEGACY, renameSource, sourceRequestConditions.getLeaseId(), null /* metadata */, null /* permissions */, null /* umask */, null /* pathHttpHeaders */, destLac, destMac, sourceConditions, customerProvidedKey, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, dataLakePathAsyncClient)); } /** * Takes in a destination and creates a DataLakePathAsyncClient with a new path * @param destinationFileSystem The destination file system * @param destinationPath The destination path * @return A DataLakePathAsyncClient */ DataLakePathAsyncClient getPathAsyncClient(String destinationFileSystem, String destinationPath) { if (destinationFileSystem == null) { destinationFileSystem = getFileSystemName(); } if (CoreUtils.isNullOrEmpty(destinationPath)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'destinationPath' can not be set to null")); } return new DataLakePathAsyncClient(getHttpPipeline(), getAccountUrl(), serviceVersion, accountName, destinationFileSystem, destinationPath, pathResourceType, prepareBuilderReplacePath(destinationFileSystem, destinationPath).buildBlockBlobAsyncClient(), customerProvidedKey); } /** * Takes in a destination path and creates a SpecializedBlobClientBuilder with a new path name * @param destinationFileSystem The destination file system * @param destinationPath The destination path * @return An updated SpecializedBlobClientBuilder */ SpecializedBlobClientBuilder prepareBuilderReplacePath(String destinationFileSystem, String destinationPath) { if (destinationFileSystem == null) { destinationFileSystem = getFileSystemName(); } String newBlobEndpoint = BlobUrlParts.parse(DataLakeImplUtils.endpointToDesiredEndpoint(getPathUrl(), "blob", "dfs")).setBlobName(destinationPath).setContainerName(destinationFileSystem).toUrl().toString(); return new SpecializedBlobClientBuilder() .pipeline(getHttpPipeline()) .endpoint(newBlobEndpoint) .serviceVersion(TransformUtils.toBlobServiceVersion(getServiceVersion())); } BlockBlobAsyncClient getBlockBlobAsyncClient() { return this.blockBlobAsyncClient; } /** * Generates a user delegation SAS for the path using the specified {@link DataLakeServiceSasSignatureValues}. * <p>See {@link DataLakeServiceSasSignatureValues} for more information on how to construct a user delegation SAS. * </p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.generateUserDelegationSas * <pre> * OffsetDateTime myExpiryTime = OffsetDateTime.now& * PathSasPermission myPermission = new PathSasPermission& * * DataLakeServiceSasSignatureValues myValues = new DataLakeServiceSasSignatureValues& * .setStartTime& * * client.generateUserDelegationSas& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.generateUserDelegationSas * * @param dataLakeServiceSasSignatureValues {@link DataLakeServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link DataLakeServiceAsyncClient * on how to get a user delegation key. * * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(DataLakeServiceSasSignatureValues dataLakeServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return generateUserDelegationSas(dataLakeServiceSasSignatureValues, userDelegationKey, getAccountName(), Context.NONE); } /** * Generates a user delegation SAS for the path using the specified {@link DataLakeServiceSasSignatureValues}. * <p>See {@link DataLakeServiceSasSignatureValues} for more information on how to construct a user delegation SAS. * </p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.generateUserDelegationSas * <pre> * OffsetDateTime myExpiryTime = OffsetDateTime.now& * PathSasPermission myPermission = new PathSasPermission& * * DataLakeServiceSasSignatureValues myValues = new DataLakeServiceSasSignatureValues& * .setStartTime& * * client.generateUserDelegationSas& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.generateUserDelegationSas * * @param dataLakeServiceSasSignatureValues {@link DataLakeServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link DataLakeServiceAsyncClient * on how to get a user delegation key. * @param accountName The account name. * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(DataLakeServiceSasSignatureValues dataLakeServiceSasSignatureValues, UserDelegationKey userDelegationKey, String accountName, Context context) { return new DataLakeSasImplUtil(dataLakeServiceSasSignatureValues, getFileSystemName(), getObjectPath(), PathResourceType.DIRECTORY.equals(this.pathResourceType)) .generateUserDelegationSas(userDelegationKey, accountName, context); } /** * Generates a service SAS for the path using the specified {@link DataLakeServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link DataLakeServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.generateSas * <pre> * OffsetDateTime expiryTime = OffsetDateTime.now& * PathSasPermission permission = new PathSasPermission& * * DataLakeServiceSasSignatureValues values = new DataLakeServiceSasSignatureValues& * .setStartTime& * * client.generateSas& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.generateSas * * @param dataLakeServiceSasSignatureValues {@link DataLakeServiceSasSignatureValues} * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(DataLakeServiceSasSignatureValues dataLakeServiceSasSignatureValues) { return generateSas(dataLakeServiceSasSignatureValues, Context.NONE); } /** * Generates a service SAS for the path using the specified {@link DataLakeServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link DataLakeServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.generateSas * <pre> * OffsetDateTime expiryTime = OffsetDateTime.now& * PathSasPermission permission = new PathSasPermission& * * DataLakeServiceSasSignatureValues values = new DataLakeServiceSasSignatureValues& * .setStartTime& * * & * client.generateSas& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.generateSas * * @param dataLakeServiceSasSignatureValues {@link DataLakeServiceSasSignatureValues} * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(DataLakeServiceSasSignatureValues dataLakeServiceSasSignatureValues, Context context) { return new DataLakeSasImplUtil(dataLakeServiceSasSignatureValues, getFileSystemName(), getObjectPath(), PathResourceType.DIRECTORY.equals(this.pathResourceType)) .generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context); } }
class DataLakePathAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(DataLakePathAsyncClient.class); final AzureDataLakeStorageRestAPIImpl dataLakeStorage; final AzureDataLakeStorageRestAPIImpl fileSystemDataLakeStorage; /** * This {@link AzureDataLakeStorageRestAPIImpl} is pointing to blob endpoint instead of dfs * in order to expose APIs that are on blob endpoint but are only functional for HNS enabled accounts. */ final AzureDataLakeStorageRestAPIImpl blobDataLakeStorage; private final String accountName; private final String fileSystemName; final String pathName; private final DataLakeServiceVersion serviceVersion; private final CpkInfo customerProvidedKey; final PathResourceType pathResourceType; final BlockBlobAsyncClient blockBlobAsyncClient; private final AzureSasCredential sasToken; /** * Package-private constructor for use by {@link DataLakePathClientBuilder}. * * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param fileSystemName The file system name. * @param pathName The path name. * @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient} */ DataLakePathAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion, String accountName, String fileSystemName, String pathName, PathResourceType pathResourceType, BlockBlobAsyncClient blockBlobAsyncClient, AzureSasCredential sasToken, CpkInfo customerProvidedKey) { this.accountName = accountName; this.fileSystemName = fileSystemName; this.pathName = Utility.urlDecode(pathName); this.pathResourceType = pathResourceType; this.blockBlobAsyncClient = blockBlobAsyncClient; this.sasToken = sasToken; this.dataLakeStorage = new AzureDataLakeStorageRestAPIImplBuilder() .pipeline(pipeline) .url(url) .fileSystem(fileSystemName) .path(this.pathName) .version(serviceVersion.getVersion()) .buildClient(); this.serviceVersion = serviceVersion; String blobUrl = DataLakeImplUtils.endpointToDesiredEndpoint(url, "blob", "dfs"); this.blobDataLakeStorage = new AzureDataLakeStorageRestAPIImplBuilder() .pipeline(pipeline) .url(blobUrl) .fileSystem(fileSystemName) .path(this.pathName) .version(serviceVersion.getVersion()) .buildClient(); this.fileSystemDataLakeStorage = new AzureDataLakeStorageRestAPIImplBuilder() .pipeline(pipeline) .url(url) .fileSystem(fileSystemName) .version(serviceVersion.getVersion()) .buildClient(); this.customerProvidedKey = customerProvidedKey; } /** * Converts the metadata into a string of format "key1=value1, key2=value2" and Base64 encodes the values. * * @param metadata The metadata. * * @return The metadata represented as a String. */ static String buildMetadataString(Map<String, String> metadata) { if (!CoreUtils.isNullOrEmpty(metadata)) { StringBuilder sb = new StringBuilder(); for (final Map.Entry<String, String> entry : metadata.entrySet()) { if (Objects.isNull(entry.getKey()) || entry.getKey().isEmpty()) { throw new IllegalArgumentException("The key for one of the metadata key-value pairs is null, " + "empty, or whitespace."); } else if (Objects.isNull(entry.getValue()) || entry.getValue().isEmpty()) { throw new IllegalArgumentException("The value for one of the metadata key-value pairs is null, " + "empty, or whitespace."); } /* The service has an internal base64 decode when metadata is copied from ADLS to Storage, so getMetadata will work as normal. Doing this encoding for the customers preserves the existing behavior of metadata. */ sb.append(entry.getKey()).append('=') .append(new String(Base64.getEncoder().encode(entry.getValue().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8)).append(','); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } else { return null; } } /** * Gets the URL of the storage account. * * @return the URL. */ String getAccountUrl() { return dataLakeStorage.getUrl(); } /** * Gets the URL of the object represented by this client on the Data Lake service. * * @return the URL. */ String getPathUrl() { return dataLakeStorage.getUrl() + "/" + fileSystemName + "/" + Utility.urlEncode(pathName); } /** * Gets the associated account name. * * @return Account name associated with this storage resource. */ public String getAccountName() { return accountName; } /** * Gets the name of the File System in which this object lives. * * @return The name of the File System. */ public String getFileSystemName() { return fileSystemName; } /** * Gets the full path of this object. * * @return The path of the object. */ String getObjectPath() { return pathName; } /** * Gets the name of this object, not including its full path. * * @return The name of the object. */ String getObjectName() { String[] pathParts = getObjectPath().split("/"); return pathParts[pathParts.length - 1]; } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return dataLakeStorage.getHttpPipeline(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public DataLakeServiceVersion getServiceVersion() { return serviceVersion; } AzureSasCredential getSasToken() { return this.sasToken; } /** * Gets the {@link CpkInfo} used to encrypt this path's content on the server. * * @return the customer provided key used for encryption. */ public CustomerProvidedKey getCustomerProvidedKey() { return new CustomerProvidedKey(customerProvidedKey.getEncryptionKey()); } CpkInfo getCpkInfo() { return this.customerProvidedKey; } /** * Creates a new {@link DataLakePathAsyncClient} with the specified {@code customerProvidedKey}. * * @param customerProvidedKey the {@link CustomerProvidedKey} for the path, * pass {@code null} to use no customer provided key. * @return a {@link DataLakePathAsyncClient} with the specified {@code customerProvidedKey}. */ /** * Creates a resource. By default, this method will not overwrite an existing path. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.create --> * <pre> * client.create& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.create --> * * <p>For more information see the * <a href="https: * Docs</a></p> * * @return A reactive response containing information about the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> create() { return create(false); } /** * Creates a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.create * <pre> * boolean overwrite = true; * client.create& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.create * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param overwrite Whether to overwrite, should data exist on the file. * * @return A reactive response containing information about the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> create(boolean overwrite) { DataLakeRequestConditions requestConditions = new DataLakeRequestConditions(); if (!overwrite) { requestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return createWithResponse(null, null, null, null, requestConditions).flatMap(FluxUtil::toMono); } /** * Creates a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.createWithResponse * <pre> * PathHttpHeaders httpHeaders = new PathHttpHeaders& * .setContentLanguage& * .setContentType& * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * .setLeaseId& * String permissions = &quot;permissions&quot;; * String umask = &quot;umask&quot;; * * client.createWithResponse& * requestConditions& * .subscribe& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.createWithResponse * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param permissions POSIX access permissions for the resource owner, the resource owning group, and others. * @param umask Restricts permissions of the resource to be created. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return A {@link Mono} containing a {@link Response} whose {@link Response * PathItem}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> createWithResponse(String permissions, String umask, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { try { return withContext(context -> createWithResponse(permissions, umask, pathResourceType, headers, metadata, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<PathInfo>> createWithResponse(String permissions, String umask, PathResourceType resourceType, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions, Context context) { requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().createWithResponseAsync(null, null, resourceType, null, null, null, null, buildMetadataString(metadata), permissions, umask, headers, lac, mac, null, customerProvidedKey, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathInfo(response.getDeserializedHeaders().getETag(), response.getDeserializedHeaders().getLastModified(), response.getDeserializedHeaders().isXMsRequestServerEncrypted() != null, response.getDeserializedHeaders().getXMsEncryptionKeySha256()))); } /** * Creates a resource if it does not exist. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.createIfNotExists --> * <pre> * client.createIfNotExists& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.createIfNotExists --> * * <p>For more information see the * <a href="https: * Docs</a></p> * * @return A reactive response signaling completion. {@link PathInfo} contains information about the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> createIfNotExists() { return createIfNotExistsWithResponse(new DataLakePathCreateOptions()).flatMap(FluxUtil::toMono); } /** * Creates a resource if it does not exist. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.createIfNotExistsWithResponse * <pre> * PathHttpHeaders headers = new PathHttpHeaders& * .setContentLanguage& * .setContentType& * String permissions = &quot;permissions&quot;; * String umask = &quot;umask&quot;; * Map&lt;String, String&gt; metadata = Collections.singletonMap& * DataLakePathCreateOptions options = new DataLakePathCreateOptions& * .setPermissions& * * client.createIfNotExistsWithResponse& * if & * System.out.println& * & * System.out.println& * & * & * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.createIfNotExistsWithResponse * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param options {@link DataLakePathCreateOptions} * @return A {@link Mono} containing {@link Response} signaling completion, whose {@link Response * contains a {@link PathInfo} containing information about the resource. If {@link Response}'s status code is * 201, a new resource was successfully created. If status code is 409, a resource already existed at this location. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> createIfNotExistsWithResponse(DataLakePathCreateOptions options) { try { return withContext(context -> createIfNotExistsWithResponse(options, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<PathInfo>> createIfNotExistsWithResponse(DataLakePathCreateOptions options, Context context) { try { options = options == null ? new DataLakePathCreateOptions() : options; options.setRequestConditions(new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD)); return createWithResponse(options.getPermissions(), options.getUmask(), pathResourceType, options.getPathHttpHeaders(), options.getMetadata(), options.getRequestConditions(), context) .onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 409, t -> { HttpResponse response = ((DataLakeStorageException) t).getResponse(); return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); }); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } /** * Package-private delete method for use by {@link DataLakeFileAsyncClient} and {@link DataLakeDirectoryAsyncClient} * * @param recursive Whether to delete all paths beneath the directory. * @param requestConditions {@link DataLakeRequestConditions} * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Mono} containing status code and HTTP headers */ Mono<Response<Void>> deleteWithResponse(Boolean recursive, DataLakeRequestConditions requestConditions, Context context) { requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().deleteWithResponseAsync(null, null, recursive, null, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, null)); } /** * Deletes paths under the resource if it exists. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.deleteIfExists --> * <pre> * client.deleteIfExists& * response -&gt; System.out.printf& * error -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.deleteIfExists --> * * <p>For more information see the * <a href="https: * Docs</a></p> * * @return a reactive response signaling completion. {@code true} indicates that the resource under the path was * successfully deleted, {@code false} indicates the resource did not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> deleteIfExists() { return deleteIfExistsWithResponse(new DataLakePathDeleteOptions()).map(response -> response.getStatusCode() != 404); } /** * Deletes all paths under the specified resource if exists. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.deleteIfExistsWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * .setLeaseId& * * DataLakePathDeleteOptions options = new DataLakePathDeleteOptions& * .setRequestConditions& * * client.deleteIfExistsWithResponse& * if & * System.out.println& * & * System.out.println& * & * & * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.deleteIfExistsWithResponse * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param options {@link DataLakePathDeleteOptions} * * @return A reactive response signaling completion. If {@link Response}'s status code is 200, the resource was * successfully deleted. If status code is 404, the resource does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteIfExistsWithResponse(DataLakePathDeleteOptions options) { try { return withContext(context -> deleteIfExistsWithResponse(options, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<Void>> deleteIfExistsWithResponse(DataLakePathDeleteOptions options, Context context) { try { options = options == null ? new DataLakePathDeleteOptions() : options; return deleteWithResponse(options.getIsRecursive(), options.getRequestConditions(), context) .onErrorResume(t -> t instanceof DataLakeStorageException && ((DataLakeStorageException) t).getStatusCode() == 404, t -> { HttpResponse response = ((DataLakeStorageException) t).getResponse(); return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); }); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } /** * Changes a resource's metadata. The specified metadata in this method will replace existing metadata. If old * values must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setMetadata * <pre> * client.setMetadata& * .subscribe& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono); } /** * Changes a resource's metadata. The specified metadata in this method will replace existing metadata. If old * values must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setMetadata * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * * client.setMetadataWithResponse& * .subscribe& * response.getStatusCode& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, DataLakeRequestConditions requestConditions) { return this.blockBlobAsyncClient.setMetadataWithResponse(metadata, Transforms.toBlobRequestConditions(requestConditions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Changes a resource's HTTP header properties. If only one HTTP header is updated, the others will all be erased. * In order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setHttpHeaders * <pre> * client.setHttpHeaders& * .setContentLanguage& * .setContentType& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setHttpHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link PathHttpHeaders} * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> setHttpHeaders(PathHttpHeaders headers) { return setHttpHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono); } /** * Changes a resource's HTTP header properties. If only one HTTP header is updated, the others will all be erased. * In order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setHttpHeadersWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * * client.setHttpHeadersWithResponse& * .setContentLanguage& * .setContentType& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setHttpHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link PathHttpHeaders} * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> setHttpHeadersWithResponse(PathHttpHeaders headers, DataLakeRequestConditions requestConditions) { return this.blockBlobAsyncClient.setHttpHeadersWithResponse(Transforms.toBlobHttpHeaders(headers), Transforms.toBlobRequestConditions(requestConditions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Returns the resource's metadata and properties. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.getProperties --> * <pre> * client.getProperties& * System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.getProperties --> * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the resource's properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> getProperties() { return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono); } /** * Returns the resource's metadata and properties. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.getPropertiesWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * * client.getPropertiesWithResponse& * response -&gt; System.out.printf& * response.getValue& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the resource's properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathProperties>> getPropertiesWithResponse(DataLakeRequestConditions requestConditions) { return blockBlobAsyncClient.getPropertiesWithResponse(Transforms.toBlobRequestConditions(requestConditions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException) .map(response -> new SimpleResponse<>(response, Transforms.toPathProperties(response.getValue()))); } /** * Determines if the path this client represents exists in the cloud. * <p>Note that this method does not guarantee that the path type (file/directory) matches expectations.</p> * <p>For example, a DataLakeFileClient representing a path to a datalake directory will return true, and vice * versa.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.exists --> * <pre> * client.exists& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.exists --> * * @return true if the path exists, false if it doesn't */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> exists() { return existsWithResponse().flatMap(FluxUtil::toMono); } /** * Determines if the path this client represents exists in the cloud. * <p>Note that this method does not guarantee that the path type (file/directory) matches expectations.</p> * <p>For example, a DataLakeFileClient representing a path to a datalake directory will return true, and vice * versa.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.existsWithResponse --> * <pre> * client.existsWithResponse& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.existsWithResponse --> * * @return true if the path exists, false if it doesn't */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> existsWithResponse() { return blockBlobAsyncClient.existsWithResponse().onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Changes the access control list, group and/or owner for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlList * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * String group = &quot;group&quot;; * String owner = &quot;owner&quot;; * * client.setAccessControlList& * response -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlList * * <p>For more information, see the * <a href="https: * * @param accessControlList A list of {@link PathAccessControlEntry} objects. * @param group The group of the resource. * @param owner The owner of the resource. * @return A reactive response containing the resource info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> setAccessControlList(List<PathAccessControlEntry> accessControlList, String group, String owner) { return setAccessControlListWithResponse(accessControlList, group, owner, null).flatMap(FluxUtil::toMono); } /** * Changes the access control list, group and/or owner for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlListWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * String group = &quot;group&quot;; * String owner = &quot;owner&quot;; * * client.setAccessControlListWithResponse& * response -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlListWithResponse * * <p>For more information, see the * <a href="https: * * @param accessControlList A list of {@link PathAccessControlEntry} objects. * @param group The group of the resource. * @param owner The owner of the resource. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the resource info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> setAccessControlListWithResponse(List<PathAccessControlEntry> accessControlList, String group, String owner, DataLakeRequestConditions requestConditions) { try { return withContext(context -> setAccessControlWithResponse(accessControlList, null, group, owner, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } /** * Changes the permissions, group and/or owner for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setPermissions * <pre> * PathPermissions permissions = new PathPermissions& * .setGroup& * .setOwner& * .setOther& * String group = &quot;group&quot;; * String owner = &quot;owner&quot;; * * client.setPermissions& * response -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setPermissions * * <p>For more information, see the * <a href="https: * * @param permissions {@link PathPermissions} * @param group The group of the resource. * @param owner The owner of the resource. * @return A reactive response containing the resource info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> setPermissions(PathPermissions permissions, String group, String owner) { return setPermissionsWithResponse(permissions, group, owner, null).flatMap(FluxUtil::toMono); } /** * Changes the permissions, group and/or owner for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setPermissionsWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * PathPermissions permissions = new PathPermissions& * .setGroup& * .setOwner& * .setOther& * String group = &quot;group&quot;; * String owner = &quot;owner&quot;; * * client.setPermissionsWithResponse& * response -&gt; System.out.printf& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setPermissionsWithResponse * * <p>For more information, see the * <a href="https: * * @param permissions {@link PathPermissions} * @param group The group of the resource. * @param owner The owner of the resource. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the resource info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> setPermissionsWithResponse(PathPermissions permissions, String group, String owner, DataLakeRequestConditions requestConditions) { try { return withContext(context -> setAccessControlWithResponse(null, permissions, group, owner, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<PathInfo>> setAccessControlWithResponse(List<PathAccessControlEntry> accessControlList, PathPermissions permissions, String group, String owner, DataLakeRequestConditions requestConditions, Context context) { requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); String permissionsString = permissions == null ? null : permissions.toString(); String accessControlListString = accessControlList == null ? null : PathAccessControlEntry.serializeList(accessControlList); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().setAccessControlWithResponseAsync(null, owner, group, permissionsString, accessControlListString, null, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathInfo(response.getDeserializedHeaders().getETag(), response.getDeserializedHeaders().getLastModified()))); } /** * Recursively sets the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlRecursive * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * client.setAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlRecursive * * <p>For more information, see the * <a href="https: * * @param accessControlList The POSIX access control list for the file or directory. * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AccessControlChangeResult> setAccessControlRecursive(List<PathAccessControlEntry> accessControlList) { return setAccessControlRecursiveWithResponse(new PathSetAccessControlRecursiveOptions(accessControlList)) .flatMap(FluxUtil::toMono); } /** * Recursively sets the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlRecursiveWithResponse * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * Integer batchSize = 2; * Integer maxBatches = 10; * boolean continueOnFailure = false; * String continuationToken = null; * Consumer&lt;Response&lt;AccessControlChanges&gt;&gt; progressHandler = * response -&gt; System.out.println& * * PathSetAccessControlRecursiveOptions options = * new PathSetAccessControlRecursiveOptions& * .setBatchSize& * .setMaxBatches& * .setContinueOnFailure& * .setContinuationToken& * .setProgressHandler& * * client.setAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.setAccessControlRecursiveWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link PathSetAccessControlRecursiveOptions} * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AccessControlChangeResult>> setAccessControlRecursiveWithResponse( PathSetAccessControlRecursiveOptions options) { try { StorageImplUtils.assertNotNull("options", options); return withContext(context -> setAccessControlRecursiveWithResponse( PathAccessControlEntry.serializeList(options.getAccessControlList()), options.getProgressHandler(), PathSetAccessControlRecursiveMode.SET, options.getBatchSize(), options.getMaxBatches(), options.isContinueOnFailure(), options.getContinuationToken(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } /** * Recursively updates the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.updateAccessControlRecursive * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * client.updateAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.updateAccessControlRecursive * * <p>For more information, see the * <a href="https: * * @param accessControlList The POSIX access control list for the file or directory. * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AccessControlChangeResult> updateAccessControlRecursive( List<PathAccessControlEntry> accessControlList) { return updateAccessControlRecursiveWithResponse(new PathUpdateAccessControlRecursiveOptions(accessControlList)) .flatMap(FluxUtil::toMono); } /** * Recursively updates the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.updateAccessControlRecursiveWithResponse * <pre> * PathAccessControlEntry pathAccessControlEntry = new PathAccessControlEntry& * .setEntityId& * .setPermissions& * List&lt;PathAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * Integer batchSize = 2; * Integer maxBatches = 10; * boolean continueOnFailure = false; * String continuationToken = null; * Consumer&lt;Response&lt;AccessControlChanges&gt;&gt; progressHandler = * response -&gt; System.out.println& * * PathUpdateAccessControlRecursiveOptions options = * new PathUpdateAccessControlRecursiveOptions& * .setBatchSize& * .setMaxBatches& * .setContinueOnFailure& * .setContinuationToken& * .setProgressHandler& * * client.updateAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.updateAccessControlRecursiveWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link PathUpdateAccessControlRecursiveOptions} * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AccessControlChangeResult>> updateAccessControlRecursiveWithResponse( PathUpdateAccessControlRecursiveOptions options) { try { StorageImplUtils.assertNotNull("options", options); return withContext(context -> setAccessControlRecursiveWithResponse( PathAccessControlEntry.serializeList(options.getAccessControlList()), options.getProgressHandler(), PathSetAccessControlRecursiveMode.MODIFY, options.getBatchSize(), options.getMaxBatches(), options.isContinueOnFailure(), options.getContinuationToken(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } /** * Recursively removes the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.removeAccessControlRecursive * <pre> * PathRemoveAccessControlEntry pathAccessControlEntry = new PathRemoveAccessControlEntry& * .setEntityId& * List&lt;PathRemoveAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * client.removeAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.removeAccessControlRecursive * * <p>For more information, see the * <a href="https: * * @param accessControlList The POSIX access control list for the file or directory. * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<AccessControlChangeResult> removeAccessControlRecursive( List<PathRemoveAccessControlEntry> accessControlList) { return removeAccessControlRecursiveWithResponse(new PathRemoveAccessControlRecursiveOptions(accessControlList)) .flatMap(FluxUtil::toMono); } /** * Recursively removes the access control on a path and all subpaths. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.removeAccessControlRecursiveWithResponse * <pre> * PathRemoveAccessControlEntry pathAccessControlEntry = new PathRemoveAccessControlEntry& * .setEntityId& * List&lt;PathRemoveAccessControlEntry&gt; pathAccessControlEntries = new ArrayList&lt;&gt;& * pathAccessControlEntries.add& * * Integer batchSize = 2; * Integer maxBatches = 10; * boolean continueOnFailure = false; * String continuationToken = null; * Consumer&lt;Response&lt;AccessControlChanges&gt;&gt; progressHandler = * response -&gt; System.out.println& * * PathRemoveAccessControlRecursiveOptions options = * new PathRemoveAccessControlRecursiveOptions& * .setBatchSize& * .setMaxBatches& * .setContinueOnFailure& * .setContinuationToken& * .setProgressHandler& * * client.removeAccessControlRecursive& * response -&gt; System.out.printf& * response.getCounters& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.removeAccessControlRecursiveWithResponse * * <p>For more information, see the * <a href="https: * * @param options {@link PathRemoveAccessControlRecursiveOptions} * @return A reactive response containing the result of the operation. * * @throws DataLakeAclChangeFailedException if a request to storage throws a * {@link DataLakeStorageException} or a {@link Exception} to wrap the exception with the continuation token. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<AccessControlChangeResult>> removeAccessControlRecursiveWithResponse( PathRemoveAccessControlRecursiveOptions options) { try { StorageImplUtils.assertNotNull("options", options); return withContext(context -> setAccessControlRecursiveWithResponse( PathRemoveAccessControlEntry.serializeList(options.getAccessControlList()), options.getProgressHandler(), PathSetAccessControlRecursiveMode.REMOVE, options.getBatchSize(), options.getMaxBatches(), options.isContinueOnFailure(), options.getContinuationToken(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<AccessControlChangeResult>> setAccessControlRecursiveWithResponse( String accessControlList, Consumer<Response<AccessControlChanges>> progressHandler, PathSetAccessControlRecursiveMode mode, Integer batchSize, Integer maxBatches, Boolean continueOnFailure, String continuationToken, Context context) { StorageImplUtils.assertNotNull("accessControlList", accessControlList); context = context == null ? Context.NONE : context; Context contextFinal = context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE); AtomicInteger directoriesSuccessfulCount = new AtomicInteger(0); AtomicInteger filesSuccessfulCount = new AtomicInteger(0); AtomicInteger failureCount = new AtomicInteger(0); AtomicInteger batchesCount = new AtomicInteger(0); return this.dataLakeStorage.getPaths().setAccessControlRecursiveWithResponseAsync(mode, null, continuationToken, continueOnFailure, batchSize, accessControlList, null, contextFinal) .onErrorMap(e -> { if (e instanceof DataLakeStorageException) { return LOGGER.logExceptionAsError(ModelHelper.changeAclRequestFailed((DataLakeStorageException) e, continuationToken)); } else if (e instanceof Exception) { return LOGGER.logExceptionAsError(ModelHelper.changeAclFailed((Exception) e, continuationToken)); } return e; }) .flatMap(response -> setAccessControlRecursiveWithResponseHelper(response, maxBatches, directoriesSuccessfulCount, filesSuccessfulCount, failureCount, batchesCount, progressHandler, accessControlList, mode, batchSize, continueOnFailure, continuationToken, null, contextFinal)); } Mono<Response<AccessControlChangeResult>> setAccessControlRecursiveWithResponseHelper( PathsSetAccessControlRecursiveResponse response, Integer maxBatches, AtomicInteger directoriesSuccessfulCount, AtomicInteger filesSuccessfulCount, AtomicInteger failureCount, AtomicInteger batchesCount, Consumer<Response<AccessControlChanges>> progressHandler, String accessControlStr, PathSetAccessControlRecursiveMode mode, Integer batchSize, Boolean continueOnFailure, String lastToken, List<AccessControlChangeFailure> batchFailures, Context context) { batchesCount.incrementAndGet(); directoriesSuccessfulCount.addAndGet(response.getValue().getDirectoriesSuccessful()); filesSuccessfulCount.addAndGet(response.getValue().getFilesSuccessful()); failureCount.addAndGet(response.getValue().getFailureCount()); if (failureCount.get() > 0 && batchFailures == null) { batchFailures = response.getValue().getFailedEntries() .stream() .map(aclFailedEntry -> new AccessControlChangeFailure() .setDirectory(aclFailedEntry.getType().equals("DIRECTORY")) .setName(aclFailedEntry.getName()) .setErrorMessage(aclFailedEntry.getErrorMessage()) ).collect(Collectors.toList()); } List<AccessControlChangeFailure> finalBatchFailures = batchFailures; /* Determine which token we should report/return/use next. If there was a token present on the response (still processing and either no errors or forceFlag set), use that one. If there were no failures or force flag set and still nothing present, we are at the end, so use that. If there were failures and no force flag set, use the last token (no token is returned in this case). */ String newToken = response.getDeserializedHeaders().getXMsContinuation(); String effectiveNextToken; if (newToken != null && !newToken.isEmpty()) { effectiveNextToken = newToken; } else { if (failureCount.get() == 0 || (continueOnFailure == null || continueOnFailure)) { effectiveNextToken = newToken; } else { effectiveNextToken = lastToken; } } if (progressHandler != null) { AccessControlChanges changes = new AccessControlChanges(); changes.setContinuationToken(effectiveNextToken); changes.setBatchFailures( response.getValue().getFailedEntries() .stream() .map(aclFailedEntry -> new AccessControlChangeFailure() .setDirectory(aclFailedEntry.getType().equals("DIRECTORY")) .setName(aclFailedEntry.getName()) .setErrorMessage(aclFailedEntry.getErrorMessage()) ).collect(Collectors.toList()) ); changes.setBatchCounters(new AccessControlChangeCounters() .setChangedDirectoriesCount(response.getValue().getDirectoriesSuccessful()) .setChangedFilesCount(response.getValue().getFilesSuccessful()) .setFailedChangesCount(response.getValue().getFailureCount())); changes.setAggregateCounters(new AccessControlChangeCounters() .setChangedDirectoriesCount(directoriesSuccessfulCount.get()) .setChangedFilesCount(filesSuccessfulCount.get()) .setFailedChangesCount(failureCount.get())); progressHandler.accept( new ResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), changes, response.getDeserializedHeaders())); } /* Determine if we are finished either because there is no new continuation (failure or finished) token or we have hit maxBatches. */ if ((newToken == null || newToken.isEmpty()) || (maxBatches != null && batchesCount.get() >= maxBatches)) { AccessControlChangeResult result = new AccessControlChangeResult() .setBatchFailures(batchFailures) .setContinuationToken(effectiveNextToken) .setCounters(new AccessControlChangeCounters() .setChangedDirectoriesCount(directoriesSuccessfulCount.get()) .setChangedFilesCount(filesSuccessfulCount.get()) .setFailedChangesCount(failureCount.get())); return Mono.just(new ResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result, response.getDeserializedHeaders() )); } return this.dataLakeStorage.getPaths().setAccessControlRecursiveWithResponseAsync(mode, null, effectiveNextToken, continueOnFailure, batchSize, accessControlStr, null, context) .onErrorMap(e -> { if (e instanceof DataLakeStorageException) { return LOGGER.logExceptionAsError(ModelHelper.changeAclRequestFailed((DataLakeStorageException) e, effectiveNextToken)); } else if (e instanceof Exception) { return LOGGER.logExceptionAsError(ModelHelper.changeAclFailed((Exception) e, effectiveNextToken)); } return e; }) .flatMap(response2 -> setAccessControlRecursiveWithResponseHelper(response2, maxBatches, directoriesSuccessfulCount, filesSuccessfulCount, failureCount, batchesCount, progressHandler, accessControlStr, mode, batchSize, continueOnFailure, effectiveNextToken, finalBatchFailures, context)); } /** * Returns the access control for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.getAccessControl --> * <pre> * client.getAccessControl& * response -&gt; System.out.printf& * PathAccessControlEntry.serializeList& * response.getOwner& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.getAccessControl --> * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the resource access control. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathAccessControl> getAccessControl() { return getAccessControlWithResponse(false, null).flatMap(FluxUtil::toMono); } /** * Returns the access control for a resource. * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.getAccessControlWithResponse * <pre> * DataLakeRequestConditions requestConditions = new DataLakeRequestConditions& * boolean userPrincipalNameReturned = false; * * client.getAccessControlWithResponse& * response -&gt; System.out.printf& * PathAccessControlEntry.serializeList& * response.getValue& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.getAccessControlWithResponse * * <p>For more information, see the * <a href="https: * * @param userPrincipalNameReturned When true, user identity values returned as User Principal Names. When false, * user identity values returned as Azure Active Directory Object IDs. Default value is false. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the resource access control. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathAccessControl>> getAccessControlWithResponse(boolean userPrincipalNameReturned, DataLakeRequestConditions requestConditions) { try { return withContext(context -> getAccessControlWithResponse(userPrincipalNameReturned, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono<Response<PathAccessControl>> getAccessControlWithResponse(boolean userPrincipalNameReturned, DataLakeRequestConditions requestConditions, Context context) { requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().getPropertiesWithResponseAsync(null, null, PathGetPropertiesAction.GET_ACCESS_CONTROL, userPrincipalNameReturned, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathAccessControl( PathAccessControlEntry.parseList(response.getDeserializedHeaders().getXMsAcl()), PathPermissions.parseSymbolic(response.getDeserializedHeaders().getXMsPermissions()), response.getDeserializedHeaders().getXMsGroup(), response.getDeserializedHeaders().getXMsOwner()))); } /** * Package-private rename method for use by {@link DataLakeFileAsyncClient} and {@link DataLakeDirectoryAsyncClient} * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath The path of the destination relative to the file system name * @param sourceRequestConditions {@link DataLakeRequestConditions} against the source. * @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DataLakePathAsyncClient} used to interact with the path created. */ Mono<Response<DataLakePathAsyncClient>> renameWithResponse(String destinationFileSystem, String destinationPath, DataLakeRequestConditions sourceRequestConditions, DataLakeRequestConditions destinationRequestConditions, Context context) { context = context == null ? Context.NONE : context; destinationRequestConditions = destinationRequestConditions == null ? new DataLakeRequestConditions() : destinationRequestConditions; sourceRequestConditions = sourceRequestConditions == null ? new DataLakeRequestConditions() : sourceRequestConditions; SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions() .setSourceIfModifiedSince(sourceRequestConditions.getIfModifiedSince()) .setSourceIfUnmodifiedSince(sourceRequestConditions.getIfUnmodifiedSince()) .setSourceIfMatch(sourceRequestConditions.getIfMatch()) .setSourceIfNoneMatch(sourceRequestConditions.getIfNoneMatch()); LeaseAccessConditions destLac = new LeaseAccessConditions() .setLeaseId(destinationRequestConditions.getLeaseId()); ModifiedAccessConditions destMac = new ModifiedAccessConditions() .setIfMatch(destinationRequestConditions.getIfMatch()) .setIfNoneMatch(destinationRequestConditions.getIfNoneMatch()) .setIfModifiedSince(destinationRequestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(destinationRequestConditions.getIfUnmodifiedSince()); DataLakePathAsyncClient dataLakePathAsyncClient = getPathAsyncClient(destinationFileSystem, destinationPath); String renameSource = "/" + this.fileSystemName + "/" + Utility.urlEncode(pathName); renameSource = this.sasToken != null ? renameSource + "?" + this.sasToken.getSignature() : renameSource; return dataLakePathAsyncClient.dataLakeStorage.getPaths().createWithResponseAsync( null /* request id */, null /* timeout */, null /* pathResourceType */, null /* continuation */, PathRenameMode.LEGACY, renameSource, sourceRequestConditions.getLeaseId(), null /* metadata */, null /* permissions */, null /* umask */, null /* pathHttpHeaders */, destLac, destMac, sourceConditions, customerProvidedKey, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, dataLakePathAsyncClient)); } /** * Takes in a destination and creates a DataLakePathAsyncClient with a new path * @param destinationFileSystem The destination file system * @param destinationPath The destination path * @return A DataLakePathAsyncClient */ DataLakePathAsyncClient getPathAsyncClient(String destinationFileSystem, String destinationPath) { if (destinationFileSystem == null) { destinationFileSystem = getFileSystemName(); } if (CoreUtils.isNullOrEmpty(destinationPath)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'destinationPath' can not be set to null")); } return new DataLakePathAsyncClient(getHttpPipeline(), getAccountUrl(), serviceVersion, accountName, destinationFileSystem, destinationPath, pathResourceType, prepareBuilderReplacePath(destinationFileSystem, destinationPath).buildBlockBlobAsyncClient(), sasToken, customerProvidedKey); } /** * Takes in a destination path and creates a SpecializedBlobClientBuilder with a new path name * @param destinationFileSystem The destination file system * @param destinationPath The destination path * @return An updated SpecializedBlobClientBuilder */ SpecializedBlobClientBuilder prepareBuilderReplacePath(String destinationFileSystem, String destinationPath) { if (destinationFileSystem == null) { destinationFileSystem = getFileSystemName(); } String newBlobEndpoint = BlobUrlParts.parse(DataLakeImplUtils.endpointToDesiredEndpoint(getPathUrl(), "blob", "dfs")).setBlobName(destinationPath).setContainerName(destinationFileSystem).toUrl().toString(); return new SpecializedBlobClientBuilder() .pipeline(getHttpPipeline()) .endpoint(newBlobEndpoint) .serviceVersion(TransformUtils.toBlobServiceVersion(getServiceVersion())); } BlockBlobAsyncClient getBlockBlobAsyncClient() { return this.blockBlobAsyncClient; } /** * Generates a user delegation SAS for the path using the specified {@link DataLakeServiceSasSignatureValues}. * <p>See {@link DataLakeServiceSasSignatureValues} for more information on how to construct a user delegation SAS. * </p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.generateUserDelegationSas * <pre> * OffsetDateTime myExpiryTime = OffsetDateTime.now& * PathSasPermission myPermission = new PathSasPermission& * * DataLakeServiceSasSignatureValues myValues = new DataLakeServiceSasSignatureValues& * .setStartTime& * * client.generateUserDelegationSas& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.generateUserDelegationSas * * @param dataLakeServiceSasSignatureValues {@link DataLakeServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link DataLakeServiceAsyncClient * on how to get a user delegation key. * * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(DataLakeServiceSasSignatureValues dataLakeServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return generateUserDelegationSas(dataLakeServiceSasSignatureValues, userDelegationKey, getAccountName(), Context.NONE); } /** * Generates a user delegation SAS for the path using the specified {@link DataLakeServiceSasSignatureValues}. * <p>See {@link DataLakeServiceSasSignatureValues} for more information on how to construct a user delegation SAS. * </p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.generateUserDelegationSas * <pre> * OffsetDateTime myExpiryTime = OffsetDateTime.now& * PathSasPermission myPermission = new PathSasPermission& * * DataLakeServiceSasSignatureValues myValues = new DataLakeServiceSasSignatureValues& * .setStartTime& * * client.generateUserDelegationSas& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.generateUserDelegationSas * * @param dataLakeServiceSasSignatureValues {@link DataLakeServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * See {@link DataLakeServiceAsyncClient * on how to get a user delegation key. * @param accountName The account name. * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateUserDelegationSas(DataLakeServiceSasSignatureValues dataLakeServiceSasSignatureValues, UserDelegationKey userDelegationKey, String accountName, Context context) { return new DataLakeSasImplUtil(dataLakeServiceSasSignatureValues, getFileSystemName(), getObjectPath(), PathResourceType.DIRECTORY.equals(this.pathResourceType)) .generateUserDelegationSas(userDelegationKey, accountName, context); } /** * Generates a service SAS for the path using the specified {@link DataLakeServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link DataLakeServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.generateSas * <pre> * OffsetDateTime expiryTime = OffsetDateTime.now& * PathSasPermission permission = new PathSasPermission& * * DataLakeServiceSasSignatureValues values = new DataLakeServiceSasSignatureValues& * .setStartTime& * * client.generateSas& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.generateSas * * @param dataLakeServiceSasSignatureValues {@link DataLakeServiceSasSignatureValues} * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(DataLakeServiceSasSignatureValues dataLakeServiceSasSignatureValues) { return generateSas(dataLakeServiceSasSignatureValues, Context.NONE); } /** * Generates a service SAS for the path using the specified {@link DataLakeServiceSasSignatureValues} * <p>Note : The client must be authenticated via {@link StorageSharedKeyCredential} * <p>See {@link DataLakeServiceSasSignatureValues} for more information on how to construct a service SAS.</p> * * <p><strong>Code Samples</strong></p> * * <!-- src_embed com.azure.storage.file.datalake.DataLakePathAsyncClient.generateSas * <pre> * OffsetDateTime expiryTime = OffsetDateTime.now& * PathSasPermission permission = new PathSasPermission& * * DataLakeServiceSasSignatureValues values = new DataLakeServiceSasSignatureValues& * .setStartTime& * * & * client.generateSas& * </pre> * <!-- end com.azure.storage.file.datalake.DataLakePathAsyncClient.generateSas * * @param dataLakeServiceSasSignatureValues {@link DataLakeServiceSasSignatureValues} * @param context Additional context that is passed through the code when generating a SAS. * * @return A {@code String} representing the SAS query parameters. */ public String generateSas(DataLakeServiceSasSignatureValues dataLakeServiceSasSignatureValues, Context context) { return new DataLakeSasImplUtil(dataLakeServiceSasSignatureValues, getFileSystemName(), getObjectPath(), PathResourceType.DIRECTORY.equals(this.pathResourceType)) .generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), context); } }
Why can't we remove the abstract and make it final, and add a private ctor?
private JsonNodeUtils(){ throw new IllegalStateException("Utility class"); }
}
private JsonNodeUtils() { }
class JsonNodeUtils { static final TypeReference<Set<String>> STRING_SET = new TypeReference<Set<String>>() { }; static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<Map<String, Object>>() { }; static String findStringValue(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isTextual()) ? value.asText() : null; } static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference, ObjectMapper mapper) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isContainerNode()) ? mapper.convertValue(value, valueTypeReference) : null; } static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isObject()) ? value : null; } }
class JsonNodeUtils { static final TypeReference<Set<String>> STRING_SET = new TypeReference<Set<String>>() { }; static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<Map<String, Object>>() { }; static String findStringValue(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isTextual()) ? value.asText() : null; } static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference, ObjectMapper mapper) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isContainerNode()) ? mapper.convertValue(value, valueTypeReference) : null; } static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isObject()) ? value : null; } }
only private ctor is enough, why add the exception?
private SerializerUtils(){ throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private SerializerUtils() { }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
no need for this exception?
private AzureStorageUtils() { throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private AzureStorageUtils() { }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
agree, seems wired and useless @jialigit would you paste the sonar issue link here and let's know which issue sonar found about this change?
private SerializerUtils(){ throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private SerializerUtils() { }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
which sonar issue is this?
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (Boolean.TRUE.equals(shareClient.exists())) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
if (Boolean.TRUE.equals(shareClient.exists())) {
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (shareClient.exists()) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
yeah, I will add the issue link here and for others.
private SerializerUtils(){ throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private SerializerUtils() { }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
This is from the sonar suggestion.
private AzureStorageUtils() { throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private AzureStorageUtils() { }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
Said Primitive type only can be used directly. Yes, this makes sense and also other places we really used the recommended way. I will paste the issue tracker here.
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (Boolean.TRUE.equals(shareClient.exists())) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
if (Boolean.TRUE.equals(shareClient.exists())) {
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (shareClient.exists()) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
Yes, we can make it final if it is not designed to be extended by sub class. And I also think this way does not make sense for utility class.
private JsonNodeUtils(){ throw new IllegalStateException("Utility class"); }
}
private JsonNodeUtils() { }
class JsonNodeUtils { static final TypeReference<Set<String>> STRING_SET = new TypeReference<Set<String>>() { }; static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<Map<String, Object>>() { }; static String findStringValue(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isTextual()) ? value.asText() : null; } static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference, ObjectMapper mapper) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isContainerNode()) ? mapper.convertValue(value, valueTypeReference) : null; } static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isObject()) ? value : null; } }
class JsonNodeUtils { static final TypeReference<Set<String>> STRING_SET = new TypeReference<Set<String>>() { }; static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<Map<String, Object>>() { }; static String findStringValue(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isTextual()) ? value.asText() : null; } static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference, ObjectMapper mapper) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isContainerNode()) ? mapper.convertValue(value, valueTypeReference) : null; } static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isObject()) ? value : null; } }
> only private ctor is enough, why add the exception? As suggestion by Sonar, this makes it more readable, and I accept it.
private SerializerUtils(){ throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private SerializerUtils() { }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
refer: https://sonarcloud.io/project/issues?directories=sdk%2Fspring%2Fspring-cloud-azure-autoconfigure%2Fsrc%2Fmain%2Fjava%2Fcom%2Fazure%2Fspring%2Fcloud%2Fautoconfigure%2Faad%2Ffilter&resolved=false&types=CODE_SMELL&id=stliu_azure-sdk-for-java&open=AXtAG3Fk00FAjxsg1BZT
private ConfigurableJWTProcessor<SecurityContext> getValidator(JWSAlgorithm jwsAlgorithm) { final ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); final JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(jwsAlgorithm, keySource); jwtProcessor.setJWSKeySelector(keySelector); jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<SecurityContext>() { @Override public void verify(JWTClaimsSet claimsSet, SecurityContext ctx) throws BadJWTException { super.verify(claimsSet, ctx); final String issuer = claimsSet.getIssuer(); if (!isAadIssuer(issuer)) { throw new BadJWTException("Invalid token issuer"); } if (Boolean.TRUE.equals(explicitAudienceCheck)) { Optional<String> matchedAudience = claimsSet.getAudience() .stream() .filter(validAudiences::contains) .findFirst(); if (matchedAudience.isPresent()) { LOGGER.debug("Matched audience: [{}]", matchedAudience.get()); } else { throw new BadJWTException("Invalid token audience. Provided value " + claimsSet.getAudience() + "does not match neither client-id nor AppIdUri."); } } } }); return jwtProcessor; }
Optional<String> matchedAudience = claimsSet.getAudience()
private ConfigurableJWTProcessor<SecurityContext> getValidator(JWSAlgorithm jwsAlgorithm) { final ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); final JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(jwsAlgorithm, keySource); jwtProcessor.setJWSKeySelector(keySelector); jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<SecurityContext>() { @Override public void verify(JWTClaimsSet claimsSet, SecurityContext ctx) throws BadJWTException { super.verify(claimsSet, ctx); final String issuer = claimsSet.getIssuer(); if (!isAadIssuer(issuer)) { throw new BadJWTException("Invalid token issuer"); } if (explicitAudienceCheck) { Optional<String> matchedAudience = claimsSet.getAudience() .stream() .filter(validAudiences::contains) .findFirst(); if (matchedAudience.isPresent()) { LOGGER.debug("Matched audience: [{}]", matchedAudience.get()); } else { throw new BadJWTException("Invalid token audience. Provided value " + claimsSet.getAudience() + "does not match neither client-id nor AppIdUri."); } } } }); return jwtProcessor; }
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final Boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException("Failed to parse active directory key discovery uri.", e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException("Failed to parse active directory key discovery uri.", e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
refer: https://sonarcloud.io/project/issues?directories=sdk%2Fspring%2Fspring-cloud-azure-autoconfigure%2Fsrc%2Fmain%2Fjava%2Fcom%2Fazure%2Fspring%2Fcloud%2Fautoconfigure%2Fkeyvault%2Fenvironment&resolved=false&types=CODE_SMELL&id=stliu_azure-sdk-for-java&open=AYAHSa95i07DX7oNprfr
public String[] getPropertyNames() { if (!caseSensitive) { return properties .keySet() .stream() .flatMap(p -> Stream.of(p, p.replace("-", "."))) .distinct() .toArray(String[]::new); } else { return properties .keySet() .toArray(new String[0]); } }
.flatMap(p -> Stream.of(p, p.replace("-", ".")))
public String[] getPropertyNames() { if (!caseSensitive) { return properties .keySet() .stream() .flatMap(p -> Stream.of(p, p.replace("-", "."))) .distinct() .toArray(String[]::new); } else { return properties .keySet() .toArray(new String[0]); } }
class KeyVaultOperation { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultOperation.class); /** * Stores the case-sensitive flag. */ private final boolean caseSensitive; /** * Stores the properties. */ private Map<String, String> properties = new HashMap<>(); /** * Stores the secret client. */ private final SecretClient secretClient; /** * Stores the secret keys. */ private final List<String> secretKeys; /** * Stores the timer object to schedule refresh task. */ private static Timer timer; /** * Constructor. * @param secretClient the Key Vault secret client. * @param refreshDuration the refresh in milliseconds (0 or less disables refresh). * @param secretKeys the secret keys to look for. * @param caseSensitive the case-sensitive flag. */ public KeyVaultOperation(final SecretClient secretClient, final Duration refreshDuration, List<String> secretKeys, boolean caseSensitive) { this.caseSensitive = caseSensitive; this.secretClient = secretClient; this.secretKeys = secretKeys; refreshProperties(); final long refreshInMillis = refreshDuration.toMillis(); if (refreshInMillis > 0) { synchronized (KeyVaultOperation.class) { if (timer != null) { try { timer.cancel(); timer.purge(); } catch (RuntimeException runtimeException) { LOGGER.error("Error of terminating Timer", runtimeException); } } timer = new Timer(true); final TimerTask task = new TimerTask() { @Override public void run() { refreshProperties(); } }; timer.scheduleAtFixedRate(task, refreshInMillis, refreshInMillis); } } } /** * Get the property. * * @param property the property to get. * @return the property value. */ public String getProperty(String property) { return properties.get(toKeyVaultSecretName(property)); } /** * Get the property names. * * @return the property names. */ /** * Refresh the properties by accessing key vault. */ private void refreshProperties() { if (secretKeys == null || secretKeys.isEmpty()) { properties = Optional.of(secretClient) .map(SecretClient::listPropertiesOfSecrets) .map(ContinuablePagedIterable::iterableByPage) .map(i -> StreamSupport.stream(i.spliterator(), false)) .orElseGet(Stream::empty) .map(PagedResponse::getElements) .flatMap(i -> StreamSupport.stream(i.spliterator(), false)) .filter(SecretProperties::isEnabled) .map(p -> secretClient.getSecret(p.getName(), p.getVersion())) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } else { properties = secretKeys.stream() .map(this::toKeyVaultSecretName) .map(secretClient::getSecret) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } } /** * For convention, we need to support all relaxed binding format from spring, these may include: * <table> * <tr><td>Spring relaxed binding names</td></tr> * <tr><td>acme.my-project.person.first-name</td></tr> * <tr><td>acme.myProject.person.firstName</td></tr> * <tr><td>acme.my_project.person.first_name</td></tr> * <tr><td>ACME_MYPROJECT_PERSON_FIRSTNAME</td></tr> * </table> * But azure key vault only allows ^[0-9a-zA-Z-]+$ and case-insensitive, so * there must be some conversion between spring names and azure key vault * names. For example, the 4 properties stated above should be converted to * acme-myproject-person-firstname in key vault. * * @param property of secret instance. * @return the value of secret with given name or null. */ private String toKeyVaultSecretName(@NonNull String property) { if (!caseSensitive) { if (property.matches("[a-z0-9A-Z-]+")) { return property.toLowerCase(Locale.US); } else if (property.matches("[A-Z0-9_]+")) { return property.toLowerCase(Locale.US).replace("_", "-"); } else { return property.toLowerCase(Locale.US) .replace("-", "") .replace("_", "") .replace("\\.", "-"); } } else { return property; } } /** * Set the properties. * * @param properties the properties. */ void setProperties(HashMap<String, String> properties) { this.properties = properties; } }
class KeyVaultOperation { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultOperation.class); /** * Stores the case-sensitive flag. */ private final boolean caseSensitive; /** * Stores the properties. */ private Map<String, String> properties = new HashMap<>(); /** * Stores the secret client. */ private final SecretClient secretClient; /** * Stores the secret keys. */ private final List<String> secretKeys; /** * Stores the timer object to schedule refresh task. */ private static Timer timer; /** * Constructor. * @param secretClient the Key Vault secret client. * @param refreshDuration the refresh in milliseconds (0 or less disables refresh). * @param secretKeys the secret keys to look for. * @param caseSensitive the case-sensitive flag. */ public KeyVaultOperation(final SecretClient secretClient, final Duration refreshDuration, List<String> secretKeys, boolean caseSensitive) { this.caseSensitive = caseSensitive; this.secretClient = secretClient; this.secretKeys = secretKeys; refreshProperties(); final long refreshInMillis = refreshDuration.toMillis(); if (refreshInMillis > 0) { synchronized (KeyVaultOperation.class) { if (timer != null) { try { timer.cancel(); timer.purge(); } catch (RuntimeException runtimeException) { LOGGER.error("Error of terminating Timer", runtimeException); } } timer = new Timer(true); final TimerTask task = new TimerTask() { @Override public void run() { refreshProperties(); } }; timer.scheduleAtFixedRate(task, refreshInMillis, refreshInMillis); } } } /** * Get the property. * * @param property the property to get. * @return the property value. */ public String getProperty(String property) { return properties.get(toKeyVaultSecretName(property)); } /** * Get the property names. * * @return the property names. */ /** * Refresh the properties by accessing key vault. */ private void refreshProperties() { if (secretKeys == null || secretKeys.isEmpty()) { properties = Optional.of(secretClient) .map(SecretClient::listPropertiesOfSecrets) .map(ContinuablePagedIterable::iterableByPage) .map(i -> StreamSupport.stream(i.spliterator(), false)) .orElseGet(Stream::empty) .map(PagedResponse::getElements) .flatMap(i -> StreamSupport.stream(i.spliterator(), false)) .filter(SecretProperties::isEnabled) .map(p -> secretClient.getSecret(p.getName(), p.getVersion())) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } else { properties = secretKeys.stream() .map(this::toKeyVaultSecretName) .map(secretClient::getSecret) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } } /** * For convention, we need to support all relaxed binding format from spring, these may include: * <table> * <tr><td>Spring relaxed binding names</td></tr> * <tr><td>acme.my-project.person.first-name</td></tr> * <tr><td>acme.myProject.person.firstName</td></tr> * <tr><td>acme.my_project.person.first_name</td></tr> * <tr><td>ACME_MYPROJECT_PERSON_FIRSTNAME</td></tr> * </table> * But azure key vault only allows ^[0-9a-zA-Z-]+$ and case-insensitive, so * there must be some conversion between spring names and azure key vault * names. For example, the 4 properties stated above should be converted to * acme-myproject-person-firstname in key vault. * * @param property of secret instance. * @return the value of secret with given name or null. */ private String toKeyVaultSecretName(@NonNull String property) { if (!caseSensitive) { if (property.matches("[a-z0-9A-Z-]+")) { return property.toLowerCase(Locale.US); } else if (property.matches("[A-Z0-9_]+")) { return property.toLowerCase(Locale.US).replace("_", "-"); } else { return property.toLowerCase(Locale.US) .replace("-", "") .replace("_", "") .replace(".", "-"); } } else { return property; } } /** * Set the properties. * * @param properties the properties. */ void setProperties(HashMap<String, String> properties) { this.properties = properties; } }
refer: https://sonarcloud.io/project/issues?directories=sdk%2Fspring%2Fspring-cloud-azure-autoconfigure%2Fsrc%2Fmain%2Fjava%2Fcom%2Fazure%2Fspring%2Fcloud%2Fautoconfigure%2Faad%2Ffilter&resolved=false&types=CODE_SMELL&id=stliu_azure-sdk-for-java&open=AXtAG3Fk00FAjxsg1BZT
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (Boolean.TRUE.equals(shareClient.exists())) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
if (Boolean.TRUE.equals(shareClient.exists())) {
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (shareClient.exists()) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
refer: https://sonarcloud.io/project/issues?directories=sdk%2Fspring%2Fspring-cloud-azure-autoconfigure%2Fsrc%2Fmain%2Fjava%2Fcom%2Fazure%2Fspring%2Fcloud%2Fautoconfigure%2Faad%2Fimplementation%2Fjackson&resolved=false&types=CODE_SMELL&id=stliu_azure-sdk-for-java&open=AXtAG3K-00FAjxsg1BbB
private AzureStorageUtils() { throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private AzureStorageUtils() { }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
I think a better is change the type of "Boolean" to `boolean` in this line https://github.com/Azure/azure-sdk-for-java/blob/5bc550c9a5de4f8ee93a5b3141500ee34be3850d/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/aad/filter/UserPrincipalManager.java#L53
private ConfigurableJWTProcessor<SecurityContext> getValidator(JWSAlgorithm jwsAlgorithm) { final ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); final JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(jwsAlgorithm, keySource); jwtProcessor.setJWSKeySelector(keySelector); jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<SecurityContext>() { @Override public void verify(JWTClaimsSet claimsSet, SecurityContext ctx) throws BadJWTException { super.verify(claimsSet, ctx); final String issuer = claimsSet.getIssuer(); if (!isAadIssuer(issuer)) { throw new BadJWTException("Invalid token issuer"); } if (Boolean.TRUE.equals(explicitAudienceCheck)) { Optional<String> matchedAudience = claimsSet.getAudience() .stream() .filter(validAudiences::contains) .findFirst(); if (matchedAudience.isPresent()) { LOGGER.debug("Matched audience: [{}]", matchedAudience.get()); } else { throw new BadJWTException("Invalid token audience. Provided value " + claimsSet.getAudience() + "does not match neither client-id nor AppIdUri."); } } } }); return jwtProcessor; }
Optional<String> matchedAudience = claimsSet.getAudience()
private ConfigurableJWTProcessor<SecurityContext> getValidator(JWSAlgorithm jwsAlgorithm) { final ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); final JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(jwsAlgorithm, keySource); jwtProcessor.setJWSKeySelector(keySelector); jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<SecurityContext>() { @Override public void verify(JWTClaimsSet claimsSet, SecurityContext ctx) throws BadJWTException { super.verify(claimsSet, ctx); final String issuer = claimsSet.getIssuer(); if (!isAadIssuer(issuer)) { throw new BadJWTException("Invalid token issuer"); } if (explicitAudienceCheck) { Optional<String> matchedAudience = claimsSet.getAudience() .stream() .filter(validAudiences::contains) .findFirst(); if (matchedAudience.isPresent()) { LOGGER.debug("Matched audience: [{}]", matchedAudience.get()); } else { throw new BadJWTException("Invalid token audience. Provided value " + claimsSet.getAudience() + "does not match neither client-id nor AppIdUri."); } } } }); return jwtProcessor; }
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final Boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException("Failed to parse active directory key discovery uri.", e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException("Failed to parse active directory key discovery uri.", e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
no need to throw exception in a private constructor
private JsonNodeUtils() { throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private JsonNodeUtils() { }
class JsonNodeUtils { static final TypeReference<Set<String>> STRING_SET = new TypeReference<Set<String>>() { }; static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<Map<String, Object>>() { }; static String findStringValue(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isTextual()) ? value.asText() : null; } static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference, ObjectMapper mapper) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isContainerNode()) ? mapper.convertValue(value, valueTypeReference) : null; } static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isObject()) ? value : null; } }
class JsonNodeUtils { static final TypeReference<Set<String>> STRING_SET = new TypeReference<Set<String>>() { }; static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<Map<String, Object>>() { }; static String findStringValue(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isTextual()) ? value.asText() : null; } static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference, ObjectMapper mapper) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isContainerNode()) ? mapper.convertValue(value, valueTypeReference) : null; } static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) { if (jsonNode == null) { return null; } JsonNode value = jsonNode.findValue(fieldName); return (value != null && value.isObject()) ? value : null; } }
I don't think that is useful, let's skip this one and only use the private constructor
private SerializerUtils(){ throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private SerializerUtils() { }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
I don't think this makes any sense
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (Boolean.TRUE.equals(shareClient.exists())) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
if (Boolean.TRUE.equals(shareClient.exists())) {
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (shareClient.exists()) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
let's not follow this suggestion
private AzureStorageUtils() { throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private AzureStorageUtils() { }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
Ok, will follow it.
private SerializerUtils(){ throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private SerializerUtils() { }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
class SerializerUtils { private static final ObjectMapper OBJECT_MAPPER; private static final TypeReference<Map<String, OAuth2AuthorizedClient>> TYPE_REFERENCE = new TypeReference<Map<String, OAuth2AuthorizedClient>>() { }; static { OBJECT_MAPPER = new ObjectMapper(); OBJECT_MAPPER.registerModule(new OAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new AadOAuth2ClientJackson2Module()); OBJECT_MAPPER.registerModule(new CoreJackson2Module()); OBJECT_MAPPER.registerModule(new JavaTimeModule()); } public static String serializeOAuth2AuthorizedClientMap(Map<String, OAuth2AuthorizedClient> authorizedClients) { String result; try { result = OBJECT_MAPPER.writeValueAsString(authorizedClients); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return result; } public static Map<String, OAuth2AuthorizedClient> deserializeOAuth2AuthorizedClientMap(String authorizedClientsString) { if (authorizedClientsString == null) { return new HashMap<>(); } Map<String, OAuth2AuthorizedClient> authorizedClients; try { authorizedClients = OBJECT_MAPPER.readValue(authorizedClientsString, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return authorizedClients; } }
Ok, will not follow this.
private AzureStorageUtils() { throw new IllegalStateException("Utility class"); }
throw new IllegalStateException("Utility class");
private AzureStorageUtils() { }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
class AzureStorageUtils { /** * Path separator character for resource location. */ public static final String PATH_DELIMITER = "/"; /** * Prefix stands for storage protocol. */ private static final String STORAGE_PROTOCOL_PREFIX = "azure-%s: /** * Whether the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource * @return true - valid Azure storage resource<br> * false - not valid Azure storage resource */ static boolean isAzureStorageResource(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); return location.toLowerCase(Locale.ROOT).startsWith(getStorageProtocolPrefix(storageType)); } /** * Get the storage protocal prefix string of storageType. * * @param storageType the storagetype of current resource * @return the exact storage protocal prefix string */ static String getStorageProtocolPrefix(StorageType storageType) { return String.format(STORAGE_PROTOCOL_PREFIX, storageType.getType()); } /** * Get the location's path. * * @param location the location represents the resource * @param storageType the storageType * @return the location's path */ static String stripProtocol(String location, StorageType storageType) { Assert.notNull(location, "Location must not be null"); assertIsAzureStorageLocation(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length()); } /** * Get the storage container(fileShare) name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the container(fileShare) name name of current location */ static String getContainerName(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); return location.substring(getStorageProtocolPrefix(storageType).length(), containerEndIndex); } /** * Get the file name from the given location. * * @param location the location represents the resource * @param storageType the storageType * @return the file name of current location */ static String getFilename(String location, StorageType storageType) { assertIsAzureStorageLocation(location, storageType); int containerEndIndex = assertContainerValid(location, storageType); if (location.endsWith(PATH_DELIMITER)) { return location.substring(++containerEndIndex, location.length() - 1); } return location.substring(++containerEndIndex); } /** * Assert the given combination of location and storageType represents a valid Azure storage resource. * * @param location the location * @param storageType the storagetype of current resource */ static void assertIsAzureStorageLocation(String location, StorageType storageType) { if (!AzureStorageUtils.isAzureStorageResource(location, storageType)) { throw new IllegalArgumentException( String.format("The location '%s' is not a valid Azure storage %s location", location, storageType.getType())); } } /** * Assert the given combination of location and storageType contains a valid Azure storage container. * * @param location the location * @param storageType the storagetype of current resource * @return the end index of container in the location */ private static int assertContainerValid(String location, StorageType storageType) { String storageProtocolPrefix = AzureStorageUtils.getStorageProtocolPrefix(storageType); int containerEndIndex = location.indexOf(PATH_DELIMITER, storageProtocolPrefix.length()); if (containerEndIndex == -1 || containerEndIndex == storageProtocolPrefix.length()) { throw new IllegalArgumentException( String.format("The location '%s' does not contain a valid container name", location)); } return containerEndIndex; } }
will ignore this suggestion
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (Boolean.TRUE.equals(shareClient.exists())) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
if (Boolean.TRUE.equals(shareClient.exists())) {
public Stream<StorageItem> listItems(String itemPrefix) { ShareClient shareClient = getShareServiceClient().getShareClient(name); if (shareClient.exists()) { return shareClient.getRootDirectoryClient().listFilesAndDirectories(itemPrefix, null, null, null) .stream() .filter(file -> !file.isDirectory()) .map(file -> new StorageItem(name, file.getName(), getStorageType())); } else { return Stream.empty(); } }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
class StorageFileContainerClient implements StorageContainerClient { private final String name; StorageFileContainerClient(String name) { this.name = name; } @Override public String getName() { return name; } @Override }
Yes, will use boolean.
private ConfigurableJWTProcessor<SecurityContext> getValidator(JWSAlgorithm jwsAlgorithm) { final ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); final JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(jwsAlgorithm, keySource); jwtProcessor.setJWSKeySelector(keySelector); jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<SecurityContext>() { @Override public void verify(JWTClaimsSet claimsSet, SecurityContext ctx) throws BadJWTException { super.verify(claimsSet, ctx); final String issuer = claimsSet.getIssuer(); if (!isAadIssuer(issuer)) { throw new BadJWTException("Invalid token issuer"); } if (Boolean.TRUE.equals(explicitAudienceCheck)) { Optional<String> matchedAudience = claimsSet.getAudience() .stream() .filter(validAudiences::contains) .findFirst(); if (matchedAudience.isPresent()) { LOGGER.debug("Matched audience: [{}]", matchedAudience.get()); } else { throw new BadJWTException("Invalid token audience. Provided value " + claimsSet.getAudience() + "does not match neither client-id nor AppIdUri."); } } } }); return jwtProcessor; }
Optional<String> matchedAudience = claimsSet.getAudience()
private ConfigurableJWTProcessor<SecurityContext> getValidator(JWSAlgorithm jwsAlgorithm) { final ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); final JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(jwsAlgorithm, keySource); jwtProcessor.setJWSKeySelector(keySelector); jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<SecurityContext>() { @Override public void verify(JWTClaimsSet claimsSet, SecurityContext ctx) throws BadJWTException { super.verify(claimsSet, ctx); final String issuer = claimsSet.getIssuer(); if (!isAadIssuer(issuer)) { throw new BadJWTException("Invalid token issuer"); } if (explicitAudienceCheck) { Optional<String> matchedAudience = claimsSet.getAudience() .stream() .filter(validAudiences::contains) .findFirst(); if (matchedAudience.isPresent()) { LOGGER.debug("Matched audience: [{}]", matchedAudience.get()); } else { throw new BadJWTException("Invalid token audience. Provided value " + claimsSet.getAudience() + "does not match neither client-id nor AppIdUri."); } } } }); return jwtProcessor; }
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final Boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException("Failed to parse active directory key discovery uri.", e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException("Failed to parse active directory key discovery uri.", e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
No need for two lines
private String action() { return String.format("Change Spring Boot version to one of the following versions %s .%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure Release train compatibility, " + "you can visit this page [%s] and check the [Release Trains] section.%nIf you want to disable this " + "check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: + "-Versions-Mapping"); }
+ "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]",
private String action() { return String.format("Change Spring Boot version to one of the following versions %s .%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure Release train compatibility, " + "you can visit this page [%s] and check the [Release Trains] section.%nIf you want to disable this " + "check, just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: + "-Versions-Mapping"); }
class AzureSpringBootVersionVerifier implements Predicate<String> { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); public static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; public static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; public AzureSpringBootVersionVerifier(List<String> acceptedVersions) { this.acceptedVersions = acceptedVersions; init(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void init() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release train", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release train"; } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { boolean matched = this.matchSpringBootVersionFromManifest(acceptedVersion); if (matched) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQuallifiedClassName = this.supportedVersions.get(versionString); if (test(fullyQuallifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate [" + versionString + "] was matched"); } return true; } } } return false; } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Version found in Boot manifest [" + version + "]"); } if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } @Override public boolean test(String fullyQuallifiedClassName) { try { if (fullyQuallifiedClassName == null) { return false; } Class.forName(fullyQuallifiedClassName); return true; } catch (ClassNotFoundException ex) { return false; } } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release train", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release train"; } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { boolean matched = this.matchSpringBootVersionFromManifest(acceptedVersion); if (matched) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQuallifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQuallifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate for Spring Boot Version of [" + versionString + "] was matched"); } return true; } } } return false; } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Version found in Boot manifest [" + version + "]"); } if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
yes
private String action() { return String.format("Change Spring Boot version to one of the following versions %s .%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure Release train compatibility, " + "you can visit this page [%s] and check the [Release Trains] section.%nIf you want to disable this " + "check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: + "-Versions-Mapping"); }
+ "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]",
private String action() { return String.format("Change Spring Boot version to one of the following versions %s .%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure Release train compatibility, " + "you can visit this page [%s] and check the [Release Trains] section.%nIf you want to disable this " + "check, just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: + "-Versions-Mapping"); }
class AzureSpringBootVersionVerifier implements Predicate<String> { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); public static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; public static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; public AzureSpringBootVersionVerifier(List<String> acceptedVersions) { this.acceptedVersions = acceptedVersions; init(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void init() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release train", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release train"; } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { boolean matched = this.matchSpringBootVersionFromManifest(acceptedVersion); if (matched) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQuallifiedClassName = this.supportedVersions.get(versionString); if (test(fullyQuallifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate [" + versionString + "] was matched"); } return true; } } } return false; } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Version found in Boot manifest [" + version + "]"); } if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } @Override public boolean test(String fullyQuallifiedClassName) { try { if (fullyQuallifiedClassName == null) { return false; } Class.forName(fullyQuallifiedClassName); return true; } catch (ClassNotFoundException ex) { return false; } } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release train", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release train"; } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { boolean matched = this.matchSpringBootVersionFromManifest(acceptedVersion); if (matched) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQuallifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQuallifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate for Spring Boot Version of [" + versionString + "] was matched"); } return true; } } } return false; } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Version found in Boot manifest [" + version + "]"); } if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
`predicate` is not a version string, `Predicate` followed by `versionString` is strange.
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { boolean matched = this.matchSpringBootVersionFromManifest(acceptedVersion); if (matched) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQuallifiedClassName = this.supportedVersions.get(versionString); if (test(fullyQuallifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate [" + versionString + "] was matched"); } return true; } } } return false; }
LOGGER.debug("Predicate [" + versionString + "] was matched");
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { boolean matched = this.matchSpringBootVersionFromManifest(acceptedVersion); if (matched) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQuallifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQuallifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate for Spring Boot Version of [" + versionString + "] was matched"); } return true; } } } return false; }
class AzureSpringBootVersionVerifier implements Predicate<String> { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); public static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; public static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; public AzureSpringBootVersionVerifier(List<String> acceptedVersions) { this.acceptedVersions = acceptedVersions; init(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void init() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release train", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release train"; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s .%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure Release train compatibility, " + "you can visit this page [%s] and check the [Release Trains] section.%nIf you want to disable this " + "check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: + "-Versions-Mapping"); } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Version found in Boot manifest [" + version + "]"); } if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } @Override public boolean test(String fullyQuallifiedClassName) { try { if (fullyQuallifiedClassName == null) { return false; } Class.forName(fullyQuallifiedClassName); return true; } catch (ClassNotFoundException ex) { return false; } } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release train", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release train"; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s .%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure Release train compatibility, " + "you can visit this page [%s] and check the [Release Trains] section.%nIf you want to disable this " + "check, just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: + "-Versions-Mapping"); } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Version found in Boot manifest [" + version + "]"); } if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
update this log
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { boolean matched = this.matchSpringBootVersionFromManifest(acceptedVersion); if (matched) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQuallifiedClassName = this.supportedVersions.get(versionString); if (test(fullyQuallifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate [" + versionString + "] was matched"); } return true; } } } return false; }
LOGGER.debug("Predicate [" + versionString + "] was matched");
private boolean springBootVersionMatches() { for (String acceptedVersion : acceptedVersions) { try { boolean matched = this.matchSpringBootVersionFromManifest(acceptedVersion); if (matched) { return true; } } catch (FileNotFoundException e) { String versionString = stripWildCardFromVersion(acceptedVersion); String fullyQuallifiedClassName = this.supportedVersions.get(versionString); if (classNameResolver.resolve(fullyQuallifiedClassName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Predicate for Spring Boot Version of [" + versionString + "] was matched"); } return true; } } } return false; }
class AzureSpringBootVersionVerifier implements Predicate<String> { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); public static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; public static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; public AzureSpringBootVersionVerifier(List<String> acceptedVersions) { this.acceptedVersions = acceptedVersions; init(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void init() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release train", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release train"; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s .%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure Release train compatibility, " + "you can visit this page [%s] and check the [Release Trains] section.%nIf you want to disable this " + "check, " + "just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: + "-Versions-Mapping"); } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Version found in Boot manifest [" + version + "]"); } if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } @Override public boolean test(String fullyQuallifiedClassName) { try { if (fullyQuallifiedClassName == null) { return false; } Class.forName(fullyQuallifiedClassName); return true; } catch (ClassNotFoundException ex) { return false; } } }
class AzureSpringBootVersionVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(AzureSpringBootVersionVerifier.class); static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5 = "org.springframework.boot.context.properties.bind.Bindable.BindRestriction"; static final String SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6 = "org.springframework.boot.autoconfigure.data.redis.ClientResourcesBuilderCustomizer"; /** * Versions supported by Spring Cloud Azure, for present is [2.5, 2.6]. Update this value if needed. */ private final Map<String, String> supportedVersions = new HashMap<>(); /** * Versionsspecified in the configuration or environment. */ private final List<String> acceptedVersions; private final ClassNameResolverPredicate classNameResolver; public AzureSpringBootVersionVerifier(List<String> acceptedVersions, ClassNameResolverPredicate classNameResolver) { this.acceptedVersions = acceptedVersions; this.classNameResolver = classNameResolver; initDefaultSupportedBootVersionCheckMeta(); } /** * Init default supported Spring Boot Version compatibility check meta data. */ private void initDefaultSupportedBootVersionCheckMeta() { supportedVersions.put("2.5", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_5); supportedVersions.put("2.6", SPRINGBOOT_CONDITIONAL_CLASS_NAME_OF_2_6); } /** * Verify the current spring-boot version * * @return Verification result of spring-boot version * @throws AzureCompatibilityNotMetException thrown if using an unsupported spring-boot version */ public VerificationResult verify() { if (this.springBootVersionMatches()) { return VerificationResult.compatible(); } else { List<VerificationResult> errors = new ArrayList<>(Collections.singleton(VerificationResult.notCompatible(this.errorDescription(), this.action()))); throw new AzureCompatibilityNotMetException(errors); } } private String errorDescription() { String versionFromManifest = this.getVersionFromManifest(); return StringUtils.hasText(versionFromManifest) ? String.format("Spring Boot [%s] is not compatible with this" + " Spring Cloud Azure release train", versionFromManifest) : "Spring Boot is not compatible with this " + "Spring Cloud Azure release train"; } private String action() { return String.format("Change Spring Boot version to one of the following versions %s .%n" + "You can find the latest Spring Boot versions here [%s]. %n" + "If you want to learn more about the Spring Cloud Azure Release train compatibility, " + "you can visit this page [%s] and check the [Release Trains] section.%nIf you want to disable this " + "check, just set the property [spring.cloud.azure.compatibility-verifier.enabled=false]", this.acceptedVersions, "https: + "-Versions-Mapping"); } String getVersionFromManifest() { return SpringBootVersion.getVersion(); } private boolean matchSpringBootVersionFromManifest(String acceptedVersion) throws FileNotFoundException { String version = this.getVersionFromManifest(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Version found in Boot manifest [" + version + "]"); } if (!StringUtils.hasText(version)) { LOGGER.info("Cannot check Boot version from manifest"); throw new FileNotFoundException("Spring Boot version not found"); } else { return version.startsWith(stripWildCardFromVersion(acceptedVersion)); } } private static String stripWildCardFromVersion(String version) { return version.endsWith(".x") ? version.substring(0, version.indexOf(".x")) : version; } }
please add more test cases for this
private String toKeyVaultSecretName(@NonNull String property) { if (!caseSensitive) { if (property.matches("[a-z0-9A-Z-]+")) { return property.toLowerCase(Locale.US); } else if (property.matches("[A-Z0-9_]+")) { return property.toLowerCase(Locale.US).replace("_", "-"); } else { return property.toLowerCase(Locale.US) .replace("-", "") .replace("_", "") .replace(".", "-"); } } else { return property; } }
} else {
private String toKeyVaultSecretName(@NonNull String property) { if (!caseSensitive) { if (property.matches("[a-z0-9A-Z-]+")) { return property.toLowerCase(Locale.US); } else if (property.matches("[A-Z0-9_]+")) { return property.toLowerCase(Locale.US).replace("_", "-"); } else { return property.toLowerCase(Locale.US) .replace("-", "") .replace("_", "") .replace(".", "-"); } } else { return property; } }
class KeyVaultOperation { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultOperation.class); /** * Stores the case-sensitive flag. */ private final boolean caseSensitive; /** * Stores the properties. */ private Map<String, String> properties = new HashMap<>(); /** * Stores the secret client. */ private final SecretClient secretClient; /** * Stores the secret keys. */ private final List<String> secretKeys; /** * Stores the timer object to schedule refresh task. */ private static Timer timer; /** * Constructor. * @param secretClient the Key Vault secret client. * @param refreshDuration the refresh in milliseconds (0 or less disables refresh). * @param secretKeys the secret keys to look for. * @param caseSensitive the case-sensitive flag. */ public KeyVaultOperation(final SecretClient secretClient, final Duration refreshDuration, List<String> secretKeys, boolean caseSensitive) { this.caseSensitive = caseSensitive; this.secretClient = secretClient; this.secretKeys = secretKeys; refreshProperties(); final long refreshInMillis = refreshDuration.toMillis(); if (refreshInMillis > 0) { synchronized (KeyVaultOperation.class) { if (timer != null) { try { timer.cancel(); timer.purge(); } catch (RuntimeException runtimeException) { LOGGER.error("Error of terminating Timer", runtimeException); } } timer = new Timer(true); final TimerTask task = new TimerTask() { @Override public void run() { refreshProperties(); } }; timer.scheduleAtFixedRate(task, refreshInMillis, refreshInMillis); } } } /** * Get the property. * * @param property the property to get. * @return the property value. */ public String getProperty(String property) { return properties.get(toKeyVaultSecretName(property)); } /** * Get the property names. * * @return the property names. */ public String[] getPropertyNames() { if (!caseSensitive) { return properties .keySet() .stream() .flatMap(p -> Stream.of(p, p.replace("-", "."))) .distinct() .toArray(String[]::new); } else { return properties .keySet() .toArray(new String[0]); } } /** * Refresh the properties by accessing key vault. */ private void refreshProperties() { if (secretKeys == null || secretKeys.isEmpty()) { properties = Optional.of(secretClient) .map(SecretClient::listPropertiesOfSecrets) .map(ContinuablePagedIterable::iterableByPage) .map(i -> StreamSupport.stream(i.spliterator(), false)) .orElseGet(Stream::empty) .map(PagedResponse::getElements) .flatMap(i -> StreamSupport.stream(i.spliterator(), false)) .filter(SecretProperties::isEnabled) .map(p -> secretClient.getSecret(p.getName(), p.getVersion())) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } else { properties = secretKeys.stream() .map(this::toKeyVaultSecretName) .map(secretClient::getSecret) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } } /** * For convention, we need to support all relaxed binding format from spring, these may include: * <table> * <tr><td>Spring relaxed binding names</td></tr> * <tr><td>acme.my-project.person.first-name</td></tr> * <tr><td>acme.myProject.person.firstName</td></tr> * <tr><td>acme.my_project.person.first_name</td></tr> * <tr><td>ACME_MYPROJECT_PERSON_FIRSTNAME</td></tr> * </table> * But azure key vault only allows ^[0-9a-zA-Z-]+$ and case-insensitive, so * there must be some conversion between spring names and azure key vault * names. For example, the 4 properties stated above should be converted to * acme-myproject-person-firstname in key vault. * * @param property of secret instance. * @return the value of secret with given name or null. */ /** * Set the properties. * * @param properties the properties. */ void setProperties(HashMap<String, String> properties) { this.properties = properties; } }
class KeyVaultOperation { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultOperation.class); /** * Stores the case-sensitive flag. */ private final boolean caseSensitive; /** * Stores the properties. */ private Map<String, String> properties = new HashMap<>(); /** * Stores the secret client. */ private final SecretClient secretClient; /** * Stores the secret keys. */ private final List<String> secretKeys; /** * Stores the timer object to schedule refresh task. */ private static Timer timer; /** * Constructor. * @param secretClient the Key Vault secret client. * @param refreshDuration the refresh in milliseconds (0 or less disables refresh). * @param secretKeys the secret keys to look for. * @param caseSensitive the case-sensitive flag. */ public KeyVaultOperation(final SecretClient secretClient, final Duration refreshDuration, List<String> secretKeys, boolean caseSensitive) { this.caseSensitive = caseSensitive; this.secretClient = secretClient; this.secretKeys = secretKeys; refreshProperties(); final long refreshInMillis = refreshDuration.toMillis(); if (refreshInMillis > 0) { synchronized (KeyVaultOperation.class) { if (timer != null) { try { timer.cancel(); timer.purge(); } catch (RuntimeException runtimeException) { LOGGER.error("Error of terminating Timer", runtimeException); } } timer = new Timer(true); final TimerTask task = new TimerTask() { @Override public void run() { refreshProperties(); } }; timer.scheduleAtFixedRate(task, refreshInMillis, refreshInMillis); } } } /** * Get the property. * * @param property the property to get. * @return the property value. */ public String getProperty(String property) { return properties.get(toKeyVaultSecretName(property)); } /** * Get the property names. * * @return the property names. */ public String[] getPropertyNames() { if (!caseSensitive) { return properties .keySet() .stream() .flatMap(p -> Stream.of(p, p.replace("-", "."))) .distinct() .toArray(String[]::new); } else { return properties .keySet() .toArray(new String[0]); } } /** * Refresh the properties by accessing key vault. */ private void refreshProperties() { if (secretKeys == null || secretKeys.isEmpty()) { properties = Optional.of(secretClient) .map(SecretClient::listPropertiesOfSecrets) .map(ContinuablePagedIterable::iterableByPage) .map(i -> StreamSupport.stream(i.spliterator(), false)) .orElseGet(Stream::empty) .map(PagedResponse::getElements) .flatMap(i -> StreamSupport.stream(i.spliterator(), false)) .filter(SecretProperties::isEnabled) .map(p -> secretClient.getSecret(p.getName(), p.getVersion())) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } else { properties = secretKeys.stream() .map(this::toKeyVaultSecretName) .map(secretClient::getSecret) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } } /** * For convention, we need to support all relaxed binding format from spring, these may include: * <table> * <tr><td>Spring relaxed binding names</td></tr> * <tr><td>acme.my-project.person.first-name</td></tr> * <tr><td>acme.myProject.person.firstName</td></tr> * <tr><td>acme.my_project.person.first_name</td></tr> * <tr><td>ACME_MYPROJECT_PERSON_FIRSTNAME</td></tr> * </table> * But azure key vault only allows ^[0-9a-zA-Z-]+$ and case-insensitive, so * there must be some conversion between spring names and azure key vault * names. For example, the 4 properties stated above should be converted to * acme-myproject-person-firstname in key vault. * * @param property of secret instance. * @return the value of secret with given name or null. */ /** * Set the properties. * * @param properties the properties. */ void setProperties(HashMap<String, String> properties) { this.properties = properties; } }
After closely looking the test cases, I think the legacy tests case can cover this. Actually, before this fix mentioned, the test fails. For lucky, we passed it after fix.
private String toKeyVaultSecretName(@NonNull String property) { if (!caseSensitive) { if (property.matches("[a-z0-9A-Z-]+")) { return property.toLowerCase(Locale.US); } else if (property.matches("[A-Z0-9_]+")) { return property.toLowerCase(Locale.US).replace("_", "-"); } else { return property.toLowerCase(Locale.US) .replace("-", "") .replace("_", "") .replace(".", "-"); } } else { return property; } }
} else {
private String toKeyVaultSecretName(@NonNull String property) { if (!caseSensitive) { if (property.matches("[a-z0-9A-Z-]+")) { return property.toLowerCase(Locale.US); } else if (property.matches("[A-Z0-9_]+")) { return property.toLowerCase(Locale.US).replace("_", "-"); } else { return property.toLowerCase(Locale.US) .replace("-", "") .replace("_", "") .replace(".", "-"); } } else { return property; } }
class KeyVaultOperation { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultOperation.class); /** * Stores the case-sensitive flag. */ private final boolean caseSensitive; /** * Stores the properties. */ private Map<String, String> properties = new HashMap<>(); /** * Stores the secret client. */ private final SecretClient secretClient; /** * Stores the secret keys. */ private final List<String> secretKeys; /** * Stores the timer object to schedule refresh task. */ private static Timer timer; /** * Constructor. * @param secretClient the Key Vault secret client. * @param refreshDuration the refresh in milliseconds (0 or less disables refresh). * @param secretKeys the secret keys to look for. * @param caseSensitive the case-sensitive flag. */ public KeyVaultOperation(final SecretClient secretClient, final Duration refreshDuration, List<String> secretKeys, boolean caseSensitive) { this.caseSensitive = caseSensitive; this.secretClient = secretClient; this.secretKeys = secretKeys; refreshProperties(); final long refreshInMillis = refreshDuration.toMillis(); if (refreshInMillis > 0) { synchronized (KeyVaultOperation.class) { if (timer != null) { try { timer.cancel(); timer.purge(); } catch (RuntimeException runtimeException) { LOGGER.error("Error of terminating Timer", runtimeException); } } timer = new Timer(true); final TimerTask task = new TimerTask() { @Override public void run() { refreshProperties(); } }; timer.scheduleAtFixedRate(task, refreshInMillis, refreshInMillis); } } } /** * Get the property. * * @param property the property to get. * @return the property value. */ public String getProperty(String property) { return properties.get(toKeyVaultSecretName(property)); } /** * Get the property names. * * @return the property names. */ public String[] getPropertyNames() { if (!caseSensitive) { return properties .keySet() .stream() .flatMap(p -> Stream.of(p, p.replace("-", "."))) .distinct() .toArray(String[]::new); } else { return properties .keySet() .toArray(new String[0]); } } /** * Refresh the properties by accessing key vault. */ private void refreshProperties() { if (secretKeys == null || secretKeys.isEmpty()) { properties = Optional.of(secretClient) .map(SecretClient::listPropertiesOfSecrets) .map(ContinuablePagedIterable::iterableByPage) .map(i -> StreamSupport.stream(i.spliterator(), false)) .orElseGet(Stream::empty) .map(PagedResponse::getElements) .flatMap(i -> StreamSupport.stream(i.spliterator(), false)) .filter(SecretProperties::isEnabled) .map(p -> secretClient.getSecret(p.getName(), p.getVersion())) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } else { properties = secretKeys.stream() .map(this::toKeyVaultSecretName) .map(secretClient::getSecret) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } } /** * For convention, we need to support all relaxed binding format from spring, these may include: * <table> * <tr><td>Spring relaxed binding names</td></tr> * <tr><td>acme.my-project.person.first-name</td></tr> * <tr><td>acme.myProject.person.firstName</td></tr> * <tr><td>acme.my_project.person.first_name</td></tr> * <tr><td>ACME_MYPROJECT_PERSON_FIRSTNAME</td></tr> * </table> * But azure key vault only allows ^[0-9a-zA-Z-]+$ and case-insensitive, so * there must be some conversion between spring names and azure key vault * names. For example, the 4 properties stated above should be converted to * acme-myproject-person-firstname in key vault. * * @param property of secret instance. * @return the value of secret with given name or null. */ /** * Set the properties. * * @param properties the properties. */ void setProperties(HashMap<String, String> properties) { this.properties = properties; } }
class KeyVaultOperation { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultOperation.class); /** * Stores the case-sensitive flag. */ private final boolean caseSensitive; /** * Stores the properties. */ private Map<String, String> properties = new HashMap<>(); /** * Stores the secret client. */ private final SecretClient secretClient; /** * Stores the secret keys. */ private final List<String> secretKeys; /** * Stores the timer object to schedule refresh task. */ private static Timer timer; /** * Constructor. * @param secretClient the Key Vault secret client. * @param refreshDuration the refresh in milliseconds (0 or less disables refresh). * @param secretKeys the secret keys to look for. * @param caseSensitive the case-sensitive flag. */ public KeyVaultOperation(final SecretClient secretClient, final Duration refreshDuration, List<String> secretKeys, boolean caseSensitive) { this.caseSensitive = caseSensitive; this.secretClient = secretClient; this.secretKeys = secretKeys; refreshProperties(); final long refreshInMillis = refreshDuration.toMillis(); if (refreshInMillis > 0) { synchronized (KeyVaultOperation.class) { if (timer != null) { try { timer.cancel(); timer.purge(); } catch (RuntimeException runtimeException) { LOGGER.error("Error of terminating Timer", runtimeException); } } timer = new Timer(true); final TimerTask task = new TimerTask() { @Override public void run() { refreshProperties(); } }; timer.scheduleAtFixedRate(task, refreshInMillis, refreshInMillis); } } } /** * Get the property. * * @param property the property to get. * @return the property value. */ public String getProperty(String property) { return properties.get(toKeyVaultSecretName(property)); } /** * Get the property names. * * @return the property names. */ public String[] getPropertyNames() { if (!caseSensitive) { return properties .keySet() .stream() .flatMap(p -> Stream.of(p, p.replace("-", "."))) .distinct() .toArray(String[]::new); } else { return properties .keySet() .toArray(new String[0]); } } /** * Refresh the properties by accessing key vault. */ private void refreshProperties() { if (secretKeys == null || secretKeys.isEmpty()) { properties = Optional.of(secretClient) .map(SecretClient::listPropertiesOfSecrets) .map(ContinuablePagedIterable::iterableByPage) .map(i -> StreamSupport.stream(i.spliterator(), false)) .orElseGet(Stream::empty) .map(PagedResponse::getElements) .flatMap(i -> StreamSupport.stream(i.spliterator(), false)) .filter(SecretProperties::isEnabled) .map(p -> secretClient.getSecret(p.getName(), p.getVersion())) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } else { properties = secretKeys.stream() .map(this::toKeyVaultSecretName) .map(secretClient::getSecret) .filter(Objects::nonNull) .collect(Collectors.toMap( s -> toKeyVaultSecretName(s.getName()), KeyVaultSecret::getValue )); } } /** * For convention, we need to support all relaxed binding format from spring, these may include: * <table> * <tr><td>Spring relaxed binding names</td></tr> * <tr><td>acme.my-project.person.first-name</td></tr> * <tr><td>acme.myProject.person.firstName</td></tr> * <tr><td>acme.my_project.person.first_name</td></tr> * <tr><td>ACME_MYPROJECT_PERSON_FIRSTNAME</td></tr> * </table> * But azure key vault only allows ^[0-9a-zA-Z-]+$ and case-insensitive, so * there must be some conversion between spring names and azure key vault * names. For example, the 4 properties stated above should be converted to * acme-myproject-person-firstname in key vault. * * @param property of secret instance. * @return the value of secret with given name or null. */ /** * Set the properties. * * @param properties the properties. */ void setProperties(HashMap<String, String> properties) { this.properties = properties; } }
to avoid confusion between sync and async, should we use `apiTextAnalyticsClient` and `batchApiTextAnalyticsClient`?
public TextAnalyticsAsyncClient buildAsyncClient() { final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final TextAnalyticsServiceVersion serviceVersion = version != null ? version : TextAnalyticsServiceVersion.getLatest(); Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { ClientOptions buildClientOptions = this.clientOptions == null ? DEFAULT_CLIENT_OPTIONS : this.clientOptions; HttpLogOptions buildLogOptions = this.httpLogOptions == null ? DEFAULT_LOG_OPTIONS : this.httpLogOptions; final String applicationId = CoreUtils.getApplicationId(buildClientOptions, buildLogOptions); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new AddHeadersPolicy(DEFAULT_HTTP_HEADERS)); policies.add(new AddHeadersFromContextPolicy()); policies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, DEFAULT_RETRY_POLICY)); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); } else if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpHeaders headers = new HttpHeaders(); buildClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new HttpLoggingPolicy(buildLogOptions)); pipeline = new HttpPipelineBuilder() .clientOptions(buildClientOptions) .httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } if (!isConsolidatedServiceVersion(version)) { final TextAnalyticsClientImpl textAnalyticsAPI = new TextAnalyticsClientImplBuilder() .endpoint(endpoint) .apiVersion(serviceVersion.getVersion()) .pipeline(pipeline) .buildClient(); return new TextAnalyticsAsyncClient(textAnalyticsAPI, serviceVersion, defaultCountryHint, defaultLanguage); } else { final MicrosoftCognitiveLanguageServiceImpl syncApiTextAnalyticsClient = new MicrosoftCognitiveLanguageServiceImplBuilder() .endpoint(endpoint) .apiVersion(serviceVersion.getVersion()) .pipeline(pipeline) .buildClient(); return new TextAnalyticsAsyncClient(syncApiTextAnalyticsClient, serviceVersion, defaultCountryHint, defaultLanguage); } }
final MicrosoftCognitiveLanguageServiceImpl syncApiTextAnalyticsClient =
public TextAnalyticsAsyncClient buildAsyncClient() { final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final TextAnalyticsServiceVersion serviceVersion = version != null ? version : TextAnalyticsServiceVersion.getLatest(); Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { ClientOptions buildClientOptions = this.clientOptions == null ? DEFAULT_CLIENT_OPTIONS : this.clientOptions; HttpLogOptions buildLogOptions = this.httpLogOptions == null ? DEFAULT_LOG_OPTIONS : this.httpLogOptions; final String applicationId = CoreUtils.getApplicationId(buildClientOptions, buildLogOptions); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new AddHeadersPolicy(DEFAULT_HTTP_HEADERS)); policies.add(new AddHeadersFromContextPolicy()); policies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, DEFAULT_RETRY_POLICY)); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); } else if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpHeaders headers = new HttpHeaders(); buildClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new HttpLoggingPolicy(buildLogOptions)); pipeline = new HttpPipelineBuilder() .clientOptions(buildClientOptions) .httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } if (!isConsolidatedServiceVersion(version)) { final TextAnalyticsClientImpl textAnalyticsAPI = new TextAnalyticsClientImplBuilder() .endpoint(endpoint) .apiVersion(serviceVersion.getVersion()) .pipeline(pipeline) .buildClient(); return new TextAnalyticsAsyncClient(textAnalyticsAPI, serviceVersion, defaultCountryHint, defaultLanguage); } else { final MicrosoftCognitiveLanguageServiceImpl batchApiTextAnalyticsClient = new MicrosoftCognitiveLanguageServiceImplBuilder() .endpoint(endpoint) .apiVersion(serviceVersion.getVersion()) .pipeline(pipeline) .buildClient(); return new TextAnalyticsAsyncClient(batchApiTextAnalyticsClient, serviceVersion, defaultCountryHint, defaultLanguage); } }
class TextAnalyticsClientBuilder implements AzureKeyCredentialTrait<TextAnalyticsClientBuilder>, ConfigurationTrait<TextAnalyticsClientBuilder>, EndpointTrait<TextAnalyticsClientBuilder>, HttpTrait<TextAnalyticsClientBuilder>, TokenCredentialTrait<TextAnalyticsClientBuilder> { private static final String DEFAULT_SCOPE = "https: private static final String NAME = "name"; private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String TEXT_ANALYTICS_PROPERTIES = "azure-ai-textanalytics.properties"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(); private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private static final HttpLogOptions DEFAULT_LOG_OPTIONS = new HttpLogOptions(); private static final HttpHeaders DEFAULT_HTTP_HEADERS = new HttpHeaders(); private final ClientLogger logger = new ClientLogger(TextAnalyticsClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private AzureKeyCredential credential; private String defaultCountryHint; private String defaultLanguage; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private TokenCredential tokenCredential; private TextAnalyticsServiceVersion version; private static final String CLIENT_NAME; private static final String CLIENT_VERSION; static { Map<String, String> properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); CLIENT_NAME = properties.getOrDefault(NAME, "UnknownName"); CLIENT_VERSION = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link TextAnalyticsClient} based on options set in the builder. Every time {@code buildClient()} is * called a new instance of {@link TextAnalyticsClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder settings are ignored * </p> * * @return A {@link TextAnalyticsClient} with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link * @throws IllegalStateException If both {@link * and {@link */ public TextAnalyticsClient buildClient() { return new TextAnalyticsClient(buildAsyncClient()); } /** * Creates a {@link TextAnalyticsAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link TextAnalyticsAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder settings are ignored. * </p> * * @return A {@link TextAnalyticsAsyncClient} with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link * @throws IllegalStateException If both {@link * and {@link */ /** * Set the default language option for one client. * * @param language default language * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder defaultLanguage(String language) { this.defaultLanguage = language; return this; } /** * Set the default country hint option for one client. * * @param countryHint default country hint * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder defaultCountryHint(String countryHint) { this.defaultCountryHint = countryHint; return this; } /** * Sets the service endpoint for the Azure Text Analytics instance. * * @param endpoint The URL of the Azure Text Analytics instance service requests to and receive responses from. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ @Override public TextAnalyticsClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * {@link TextAnalyticsClientBuilder}. * * @param keyCredential {@link AzureKeyCredential} API key credential * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null */ @Override public TextAnalyticsClientBuilder credential(AzureKeyCredential keyCredential) { this.credential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ @Override public TextAnalyticsClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Gets the default Azure Text Analytics headers and query parameters allow list. * * @return The default {@link HttpLogOptions} allow list. */ public static HttpLogOptions getDefaultLogOptions() { return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @return The updated TextAnalyticsClientBuilder object. * @see HttpClientOptions */ @Override public TextAnalyticsClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param policy A {@link HttpPipelinePolicy pipeline policy}. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code policy} is null. */ public TextAnalyticsClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy, "'policy' cannot be null."); if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param client The {@link HttpClient} to use for requests. * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder 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 {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * TextAnalyticsClientBuilder * TextAnalyticsClient}. * * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder 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 used to * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided {@link TextAnalyticsClientBuilder * build {@link TextAnalyticsAsyncClient} or {@link TextAnalyticsClient}. * <p> * Setting this is mutually exclusive with using {@link * * @param retryPolicy user's retry policy applied to each request. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link TextAnalyticsServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link TextAnalyticsServiceVersion} of the service to be used when making requests. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder serviceVersion(TextAnalyticsServiceVersion version) { this.version = version; return this; } private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_03_01; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); } }
class TextAnalyticsClientBuilder implements AzureKeyCredentialTrait<TextAnalyticsClientBuilder>, ConfigurationTrait<TextAnalyticsClientBuilder>, EndpointTrait<TextAnalyticsClientBuilder>, HttpTrait<TextAnalyticsClientBuilder>, TokenCredentialTrait<TextAnalyticsClientBuilder> { private static final String DEFAULT_SCOPE = "https: private static final String NAME = "name"; private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String TEXT_ANALYTICS_PROPERTIES = "azure-ai-textanalytics.properties"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(); private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private static final HttpLogOptions DEFAULT_LOG_OPTIONS = new HttpLogOptions(); private static final HttpHeaders DEFAULT_HTTP_HEADERS = new HttpHeaders(); private final ClientLogger logger = new ClientLogger(TextAnalyticsClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private AzureKeyCredential credential; private String defaultCountryHint; private String defaultLanguage; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private TokenCredential tokenCredential; private TextAnalyticsServiceVersion version; private static final String CLIENT_NAME; private static final String CLIENT_VERSION; static { Map<String, String> properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); CLIENT_NAME = properties.getOrDefault(NAME, "UnknownName"); CLIENT_VERSION = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link TextAnalyticsClient} based on options set in the builder. Every time {@code buildClient()} is * called a new instance of {@link TextAnalyticsClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder settings are ignored * </p> * * @return A {@link TextAnalyticsClient} with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link * @throws IllegalStateException If both {@link * and {@link */ public TextAnalyticsClient buildClient() { return new TextAnalyticsClient(buildAsyncClient()); } /** * Creates a {@link TextAnalyticsAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link TextAnalyticsAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder settings are ignored. * </p> * * @return A {@link TextAnalyticsAsyncClient} with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link * @throws IllegalStateException If both {@link * and {@link */ /** * Set the default language option for one client. * * @param language default language * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder defaultLanguage(String language) { this.defaultLanguage = language; return this; } /** * Set the default country hint option for one client. * * @param countryHint default country hint * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder defaultCountryHint(String countryHint) { this.defaultCountryHint = countryHint; return this; } /** * Sets the service endpoint for the Azure Text Analytics instance. * * @param endpoint The URL of the Azure Text Analytics instance service requests to and receive responses from. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ @Override public TextAnalyticsClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * {@link TextAnalyticsClientBuilder}. * * @param keyCredential {@link AzureKeyCredential} API key credential * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null */ @Override public TextAnalyticsClientBuilder credential(AzureKeyCredential keyCredential) { this.credential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ @Override public TextAnalyticsClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Gets the default Azure Text Analytics headers and query parameters allow list. * * @return The default {@link HttpLogOptions} allow list. */ public static HttpLogOptions getDefaultLogOptions() { return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @return The updated TextAnalyticsClientBuilder object. * @see HttpClientOptions */ @Override public TextAnalyticsClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param policy A {@link HttpPipelinePolicy pipeline policy}. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code policy} is null. */ public TextAnalyticsClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy, "'policy' cannot be null."); if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param client The {@link HttpClient} to use for requests. * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder 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 {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * TextAnalyticsClientBuilder * TextAnalyticsClient}. * * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder 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 used to * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided {@link TextAnalyticsClientBuilder * build {@link TextAnalyticsAsyncClient} or {@link TextAnalyticsClient}. * <p> * Setting this is mutually exclusive with using {@link * * @param retryPolicy user's retry policy applied to each request. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link TextAnalyticsServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link TextAnalyticsServiceVersion} of the service to be used when making requests. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder serviceVersion(TextAnalyticsServiceVersion version) { this.version = version; return this; } private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); } }
like the name. WIll use it.
public TextAnalyticsAsyncClient buildAsyncClient() { final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final TextAnalyticsServiceVersion serviceVersion = version != null ? version : TextAnalyticsServiceVersion.getLatest(); Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { ClientOptions buildClientOptions = this.clientOptions == null ? DEFAULT_CLIENT_OPTIONS : this.clientOptions; HttpLogOptions buildLogOptions = this.httpLogOptions == null ? DEFAULT_LOG_OPTIONS : this.httpLogOptions; final String applicationId = CoreUtils.getApplicationId(buildClientOptions, buildLogOptions); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new AddHeadersPolicy(DEFAULT_HTTP_HEADERS)); policies.add(new AddHeadersFromContextPolicy()); policies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, DEFAULT_RETRY_POLICY)); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); } else if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpHeaders headers = new HttpHeaders(); buildClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new HttpLoggingPolicy(buildLogOptions)); pipeline = new HttpPipelineBuilder() .clientOptions(buildClientOptions) .httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } if (!isConsolidatedServiceVersion(version)) { final TextAnalyticsClientImpl textAnalyticsAPI = new TextAnalyticsClientImplBuilder() .endpoint(endpoint) .apiVersion(serviceVersion.getVersion()) .pipeline(pipeline) .buildClient(); return new TextAnalyticsAsyncClient(textAnalyticsAPI, serviceVersion, defaultCountryHint, defaultLanguage); } else { final MicrosoftCognitiveLanguageServiceImpl syncApiTextAnalyticsClient = new MicrosoftCognitiveLanguageServiceImplBuilder() .endpoint(endpoint) .apiVersion(serviceVersion.getVersion()) .pipeline(pipeline) .buildClient(); return new TextAnalyticsAsyncClient(syncApiTextAnalyticsClient, serviceVersion, defaultCountryHint, defaultLanguage); } }
final MicrosoftCognitiveLanguageServiceImpl syncApiTextAnalyticsClient =
public TextAnalyticsAsyncClient buildAsyncClient() { final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final TextAnalyticsServiceVersion serviceVersion = version != null ? version : TextAnalyticsServiceVersion.getLatest(); Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { ClientOptions buildClientOptions = this.clientOptions == null ? DEFAULT_CLIENT_OPTIONS : this.clientOptions; HttpLogOptions buildLogOptions = this.httpLogOptions == null ? DEFAULT_LOG_OPTIONS : this.httpLogOptions; final String applicationId = CoreUtils.getApplicationId(buildClientOptions, buildLogOptions); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new AddHeadersPolicy(DEFAULT_HTTP_HEADERS)); policies.add(new AddHeadersFromContextPolicy()); policies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, DEFAULT_RETRY_POLICY)); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); } else if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(perRetryPolicies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpHeaders headers = new HttpHeaders(); buildClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } policies.add(new HttpLoggingPolicy(buildLogOptions)); pipeline = new HttpPipelineBuilder() .clientOptions(buildClientOptions) .httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } if (!isConsolidatedServiceVersion(version)) { final TextAnalyticsClientImpl textAnalyticsAPI = new TextAnalyticsClientImplBuilder() .endpoint(endpoint) .apiVersion(serviceVersion.getVersion()) .pipeline(pipeline) .buildClient(); return new TextAnalyticsAsyncClient(textAnalyticsAPI, serviceVersion, defaultCountryHint, defaultLanguage); } else { final MicrosoftCognitiveLanguageServiceImpl batchApiTextAnalyticsClient = new MicrosoftCognitiveLanguageServiceImplBuilder() .endpoint(endpoint) .apiVersion(serviceVersion.getVersion()) .pipeline(pipeline) .buildClient(); return new TextAnalyticsAsyncClient(batchApiTextAnalyticsClient, serviceVersion, defaultCountryHint, defaultLanguage); } }
class TextAnalyticsClientBuilder implements AzureKeyCredentialTrait<TextAnalyticsClientBuilder>, ConfigurationTrait<TextAnalyticsClientBuilder>, EndpointTrait<TextAnalyticsClientBuilder>, HttpTrait<TextAnalyticsClientBuilder>, TokenCredentialTrait<TextAnalyticsClientBuilder> { private static final String DEFAULT_SCOPE = "https: private static final String NAME = "name"; private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String TEXT_ANALYTICS_PROPERTIES = "azure-ai-textanalytics.properties"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(); private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private static final HttpLogOptions DEFAULT_LOG_OPTIONS = new HttpLogOptions(); private static final HttpHeaders DEFAULT_HTTP_HEADERS = new HttpHeaders(); private final ClientLogger logger = new ClientLogger(TextAnalyticsClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private AzureKeyCredential credential; private String defaultCountryHint; private String defaultLanguage; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private TokenCredential tokenCredential; private TextAnalyticsServiceVersion version; private static final String CLIENT_NAME; private static final String CLIENT_VERSION; static { Map<String, String> properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); CLIENT_NAME = properties.getOrDefault(NAME, "UnknownName"); CLIENT_VERSION = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link TextAnalyticsClient} based on options set in the builder. Every time {@code buildClient()} is * called a new instance of {@link TextAnalyticsClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder settings are ignored * </p> * * @return A {@link TextAnalyticsClient} with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link * @throws IllegalStateException If both {@link * and {@link */ public TextAnalyticsClient buildClient() { return new TextAnalyticsClient(buildAsyncClient()); } /** * Creates a {@link TextAnalyticsAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link TextAnalyticsAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder settings are ignored. * </p> * * @return A {@link TextAnalyticsAsyncClient} with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link * @throws IllegalStateException If both {@link * and {@link */ /** * Set the default language option for one client. * * @param language default language * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder defaultLanguage(String language) { this.defaultLanguage = language; return this; } /** * Set the default country hint option for one client. * * @param countryHint default country hint * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder defaultCountryHint(String countryHint) { this.defaultCountryHint = countryHint; return this; } /** * Sets the service endpoint for the Azure Text Analytics instance. * * @param endpoint The URL of the Azure Text Analytics instance service requests to and receive responses from. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ @Override public TextAnalyticsClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * {@link TextAnalyticsClientBuilder}. * * @param keyCredential {@link AzureKeyCredential} API key credential * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null */ @Override public TextAnalyticsClientBuilder credential(AzureKeyCredential keyCredential) { this.credential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ @Override public TextAnalyticsClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Gets the default Azure Text Analytics headers and query parameters allow list. * * @return The default {@link HttpLogOptions} allow list. */ public static HttpLogOptions getDefaultLogOptions() { return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @return The updated TextAnalyticsClientBuilder object. * @see HttpClientOptions */ @Override public TextAnalyticsClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param policy A {@link HttpPipelinePolicy pipeline policy}. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code policy} is null. */ public TextAnalyticsClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy, "'policy' cannot be null."); if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param client The {@link HttpClient} to use for requests. * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder 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 {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * TextAnalyticsClientBuilder * TextAnalyticsClient}. * * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder 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 used to * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided {@link TextAnalyticsClientBuilder * build {@link TextAnalyticsAsyncClient} or {@link TextAnalyticsClient}. * <p> * Setting this is mutually exclusive with using {@link * * @param retryPolicy user's retry policy applied to each request. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link TextAnalyticsServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link TextAnalyticsServiceVersion} of the service to be used when making requests. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder serviceVersion(TextAnalyticsServiceVersion version) { this.version = version; return this; } private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_03_01; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); } }
class TextAnalyticsClientBuilder implements AzureKeyCredentialTrait<TextAnalyticsClientBuilder>, ConfigurationTrait<TextAnalyticsClientBuilder>, EndpointTrait<TextAnalyticsClientBuilder>, HttpTrait<TextAnalyticsClientBuilder>, TokenCredentialTrait<TextAnalyticsClientBuilder> { private static final String DEFAULT_SCOPE = "https: private static final String NAME = "name"; private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String TEXT_ANALYTICS_PROPERTIES = "azure-ai-textanalytics.properties"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(); private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); private static final HttpLogOptions DEFAULT_LOG_OPTIONS = new HttpLogOptions(); private static final HttpHeaders DEFAULT_HTTP_HEADERS = new HttpHeaders(); private final ClientLogger logger = new ClientLogger(TextAnalyticsClientBuilder.class); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private ClientOptions clientOptions; private Configuration configuration; private AzureKeyCredential credential; private String defaultCountryHint; private String defaultLanguage; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private RetryPolicy retryPolicy; private RetryOptions retryOptions; private TokenCredential tokenCredential; private TextAnalyticsServiceVersion version; private static final String CLIENT_NAME; private static final String CLIENT_VERSION; static { Map<String, String> properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); CLIENT_NAME = properties.getOrDefault(NAME, "UnknownName"); CLIENT_VERSION = properties.getOrDefault(VERSION, "UnknownVersion"); } /** * Creates a {@link TextAnalyticsClient} based on options set in the builder. Every time {@code buildClient()} is * called a new instance of {@link TextAnalyticsClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder settings are ignored * </p> * * @return A {@link TextAnalyticsClient} with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link * @throws IllegalStateException If both {@link * and {@link */ public TextAnalyticsClient buildClient() { return new TextAnalyticsClient(buildAsyncClient()); } /** * Creates a {@link TextAnalyticsAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient()} is called a new instance of {@link TextAnalyticsAsyncClient} is created. * * <p> * If {@link * endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder settings are ignored. * </p> * * @return A {@link TextAnalyticsAsyncClient} with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link * @throws IllegalStateException If both {@link * and {@link */ /** * Set the default language option for one client. * * @param language default language * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder defaultLanguage(String language) { this.defaultLanguage = language; return this; } /** * Set the default country hint option for one client. * * @param countryHint default country hint * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder defaultCountryHint(String countryHint) { this.defaultCountryHint = countryHint; return this; } /** * Sets the service endpoint for the Azure Text Analytics instance. * * @param endpoint The URL of the Azure Text Analytics instance service requests to and receive responses from. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ @Override public TextAnalyticsClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * {@link TextAnalyticsClientBuilder}. * * @param keyCredential {@link AzureKeyCredential} API key credential * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null */ @Override public TextAnalyticsClientBuilder credential(AzureKeyCredential keyCredential) { this.credential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ @Override public TextAnalyticsClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Gets the default Azure Text Analytics headers and query parameters allow list. * * @return The default {@link HttpLogOptions} allow list. */ public static HttpLogOptions getDefaultLogOptions() { return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); } /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @return The updated TextAnalyticsClientBuilder object. * @see HttpClientOptions */ @Override public TextAnalyticsClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param policy A {@link HttpPipelinePolicy pipeline policy}. * @return The updated {@link TextAnalyticsClientBuilder} object. * @throws NullPointerException If {@code policy} is null. */ public TextAnalyticsClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy, "'policy' cannot be null."); if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param client The {@link HttpClient} to use for requests. * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder 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 {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * If {@code pipeline} is set, all other settings are ignored, aside from {@link * TextAnalyticsClientBuilder * TextAnalyticsClient}. * * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder 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 used to * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * <p> * The default retry policy will be used if not provided {@link TextAnalyticsClientBuilder * build {@link TextAnalyticsAsyncClient} or {@link TextAnalyticsClient}. * <p> * Setting this is mutually exclusive with using {@link * * @param retryPolicy user's retry policy applied to each request. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * * @return The updated {@link TextAnalyticsClientBuilder} object. */ @Override public TextAnalyticsClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link TextAnalyticsServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link TextAnalyticsServiceVersion} of the service to be used when making requests. * @return The updated {@link TextAnalyticsClientBuilder} object. */ public TextAnalyticsClientBuilder serviceVersion(TextAnalyticsServiceVersion version) { this.version = version; return this; } private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); } }
Is the idea here that samples run for different service versions?
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_API_KEY"))) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT")) .buildClient(); String document = "The hotel was dark and unclean. I like Microsoft."; final DocumentSentiment documentSentiment = client.analyzeSentiment(document); SentimentConfidenceScores scores = documentSentiment.getConfidenceScores(); System.out.printf( "Recognized document sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n", documentSentiment.getSentiment(), scores.getPositive(), scores.getNeutral(), scores.getNegative()); documentSentiment.getSentences().forEach(sentenceSentiment -> { SentimentConfidenceScores sentenceScores = sentenceSentiment.getConfidenceScores(); System.out.printf("Recognized sentence sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n", sentenceSentiment.getSentiment(), sentenceScores.getPositive(), sentenceScores.getNeutral(), sentenceScores.getNegative()); }); }
.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_API_KEY")))
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); String document = "The hotel was dark and unclean. I like Microsoft."; final DocumentSentiment documentSentiment = client.analyzeSentiment(document); SentimentConfidenceScores scores = documentSentiment.getConfidenceScores(); System.out.printf( "Recognized document sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n", documentSentiment.getSentiment(), scores.getPositive(), scores.getNeutral(), scores.getNegative()); documentSentiment.getSentences().forEach(sentenceSentiment -> { SentimentConfidenceScores sentenceScores = sentenceSentiment.getConfidenceScores(); System.out.printf("Recognized sentence sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n", sentenceSentiment.getSentiment(), sentenceScores.getPositive(), sentenceScores.getNeutral(), sentenceScores.getNegative()); }); }
class AnalyzeSentiment { /** * Main method to invoke this demo about how to analyze the sentiment of document. * * @param args Unused arguments to the program. */ }
class AnalyzeSentiment { /** * Main method to invoke this demo about how to analyze the sentiment of document. * * @param args Unused arguments to the program. */ }
Revert the changes in samples.
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_API_KEY"))) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT")) .buildClient(); String document = "The hotel was dark and unclean. I like Microsoft."; final DocumentSentiment documentSentiment = client.analyzeSentiment(document); SentimentConfidenceScores scores = documentSentiment.getConfidenceScores(); System.out.printf( "Recognized document sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n", documentSentiment.getSentiment(), scores.getPositive(), scores.getNeutral(), scores.getNegative()); documentSentiment.getSentences().forEach(sentenceSentiment -> { SentimentConfidenceScores sentenceScores = sentenceSentiment.getConfidenceScores(); System.out.printf("Recognized sentence sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n", sentenceSentiment.getSentiment(), sentenceScores.getPositive(), sentenceScores.getNeutral(), sentenceScores.getNegative()); }); }
.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_API_KEY")))
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); String document = "The hotel was dark and unclean. I like Microsoft."; final DocumentSentiment documentSentiment = client.analyzeSentiment(document); SentimentConfidenceScores scores = documentSentiment.getConfidenceScores(); System.out.printf( "Recognized document sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n", documentSentiment.getSentiment(), scores.getPositive(), scores.getNeutral(), scores.getNegative()); documentSentiment.getSentences().forEach(sentenceSentiment -> { SentimentConfidenceScores sentenceScores = sentenceSentiment.getConfidenceScores(); System.out.printf("Recognized sentence sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n", sentenceSentiment.getSentiment(), sentenceScores.getPositive(), sentenceScores.getNeutral(), sentenceScores.getNegative()); }); }
class AnalyzeSentiment { /** * Main method to invoke this demo about how to analyze the sentiment of document. * * @param args Unused arguments to the program. */ }
class AnalyzeSentiment { /** * Main method to invoke this demo about how to analyze the sentiment of document. * * @param args Unused arguments to the program. */ }
has a user always not been able to override the stringIndexType default?
private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)
private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
this should include fhirVersion if you're exposing fhirBundle on the result
private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
return (HealthcareTaskParameters) new HealthcareTaskParameters()
private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
includeOpinionMining?
private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters()
private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
why commented out?
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
what's the behavior in the java library if a target is not returned by the service?
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
should the version have preview appended to it?
private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_04_01; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); }
serviceVersion = TextAnalyticsServiceVersion.V2022_04_01;
private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); }
class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline}
class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline}
Yes. The StringIndexType is default the UTF16CODE_UNIT until StringIndexType is on. Currently. Java still not yet make the StringIndexType publicly
private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)
private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Will create a separate PR to address it.
private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
return (HealthcareTaskParameters) new HealthcareTaskParameters()
private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Good catch!
private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters()
private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
uncommented.
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Java will throw an error if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); }
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Would it make sense to throw the error message(s) that the service returns in the error object? While the error you throw now is accurate, it kind of focuses more on the internal implementation.
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
We should generally avoid the use of [magic number ](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) and replace it with what it stands for.
public static String parseOperationId(String operationLocation) { if (!CoreUtils.isNullOrEmpty(operationLocation)) { int lastIndex = operationLocation.lastIndexOf('/'); if (lastIndex != -1) { return operationLocation.substring(lastIndex + 1, lastIndex + 37); } } throw LOGGER.logExceptionAsError( new RuntimeException("Failed to parse operation header for operation Id from: " + operationLocation)); }
return operationLocation.substring(lastIndex + 1, lastIndex + 37);
public static String parseOperationId(String operationLocation) { if (!CoreUtils.isNullOrEmpty(operationLocation)) { final int indexBeforeOperationId = operationLocation.lastIndexOf('/'); if (indexBeforeOperationId != -1) { return operationLocation.substring(indexBeforeOperationId + 1, indexBeforeOperationId + OPERATION_ID_LENGTH); } } throw LOGGER.logExceptionAsError( new RuntimeException("Failed to parse operation header for operation Id from: " + operationLocation)); }
class Utility { public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(30); private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final int NEUTRAL_SCORE_ZERO = 0; private static final String DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP = " private static final Pattern PATTERN; static { PATTERN = Pattern.compile(DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP); } private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is null. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Mapping a {@link ErrorResponseException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ public static Throwable mapToHttpResponseExceptionIfExists(Throwable throwable) { if (throwable instanceof ErrorResponseException) { ErrorResponseException errorException = (ErrorResponseException) throwable; final ErrorResponse errorResponse = errorException.getValue(); com.azure.ai.textanalytics.models.TextAnalyticsError textAnalyticsError = null; if (errorResponse != null && errorResponse.getError() != null) { textAnalyticsError = toTextAnalyticsError(errorResponse.getError()); } return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), textAnalyticsError); } return throwable; } /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link Error} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link Error inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param error the {@link Error} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static TextAnalyticsError toTextAnalyticsError(Error error) { final InnerErrorModel innerError = error.getInnererror(); if (innerError == null) { final ErrorCode errorCode = error.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCode == null ? null : errorCode.toString()), error.getMessage(), error.getTarget()); } final InnerErrorCode innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } public static TextAnalyticsWarning toTextAnalyticsWarning( DocumentWarning warning) { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } /** * Extracts the operation ID from the 'operation-location' URL. An example of 'operation-location' is * https: * * @param operationLocation The URL specified in the 'Operation-Location' response header containing the * operation ID used to track the progress and obtain the ID of the analyze operation. * * @return The operation ID that tracks the long running operation progress. */ /** * Extract the next pagination link which contains the request parameter values, into map, * such as '$skip=20' and '$top=2'. * * @param nextLink the next pagination link. * * @return A map that holds the request parameter value of next pagination link. */ public static Map<String, Object> parseNextLink(String nextLink) { if (!CoreUtils.isNullOrEmpty(nextLink)) { final Map<String, Object> parameterMap = new HashMap<>(); final String[] strings = nextLink.split("\\?", 2); final String[] parameters = strings[1].split("&"); for (String parameter : parameters) { final String[] parameterPair = parameter.split("="); final String key = parameterPair[0]; final String value = parameterPair[1]; if ("showStats".equals(key)) { parameterMap.put(key, value); } else if ("$skip".equals(key) || "$top".equals(key)) { parameterMap.put(key, Integer.valueOf(value)); } } return parameterMap; } return new HashMap<>(); } public static Response<AnalyzeSentimentResultCollection> toAnalyzeSentimentResultCollectionResponse( Response<SentimentResponse> response) { return new SimpleResponse<>(response, toAnalyzeSentimentResultCollection(response.getValue())); } public static Response<AnalyzeSentimentResultCollection> toAnalyzeSentimentResultCollectionResponse2( Response<AnalyzeTextTaskResult> response) { return new SimpleResponse<>(response, toAnalyzeSentimentResultCollection(((SentimentTaskResult) response.getValue()).getResults())); } public static Response<DetectLanguageResultCollection> toDetectLanguageResultCollectionResponse( Response<LanguageResult> response) { final LanguageResult languageResult = response.getValue(); final List<DetectLanguageResult> detectLanguageResults = new ArrayList<>(); for (DocumentLanguage documentLanguage : languageResult.getDocuments()) { com.azure.ai.textanalytics.implementation.models.DetectedLanguage detectedLanguage = documentLanguage.getDetectedLanguage(); final List<TextAnalyticsWarning> warnings = documentLanguage.getWarnings().stream() .map(warning -> toTextAnalyticsWarning(warning)) .collect(Collectors.toList()); detectLanguageResults.add(new DetectLanguageResult( documentLanguage.getId(), documentLanguage.getStatistics() == null ? null : toTextDocumentStatistics(documentLanguage.getStatistics()), null, new DetectedLanguage(detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore(), new IterableStream<>(warnings)))); } for (DocumentError documentError : languageResult.getErrors()) { detectLanguageResults.add(new DetectLanguageResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new DetectLanguageResultCollection(detectLanguageResults, languageResult.getModelVersion(), languageResult.getStatistics() == null ? null : toBatchStatistics(languageResult.getStatistics()))); } public static Response<DetectLanguageResultCollection> toDetectLanguageResultCollectionResponse2( Response<AnalyzeTextTaskResult> response) { final LanguageDetectionResult languageResult = ((LanguageDetectionTaskResult) response.getValue()).getResults(); final List<DetectLanguageResult> detectLanguageResults = new ArrayList<>(); for (LanguageDetectionDocumentResult documentLanguage : languageResult.getDocuments()) { com.azure.ai.textanalytics.implementation.models.DetectedLanguage detectedLanguage = documentLanguage.getDetectedLanguage(); final List<TextAnalyticsWarning> warnings = documentLanguage.getWarnings() .stream() .map(warning -> toTextAnalyticsWarning(warning)) .collect(Collectors.toList()); detectLanguageResults.add(new DetectLanguageResult( documentLanguage.getId(), documentLanguage.getStatistics() == null ? null : toTextDocumentStatistics(documentLanguage.getStatistics()), null, new DetectedLanguage(detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore(), new IterableStream<>(warnings) ))); } for (DocumentError documentError : languageResult.getErrors()) { detectLanguageResults.add(new DetectLanguageResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new DetectLanguageResultCollection(detectLanguageResults, languageResult.getModelVersion(), languageResult.getStatistics() == null ? null : toBatchStatistics(languageResult.getStatistics()))); } public static Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final Response<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (KeyPhraseResultDocumentsItem 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 -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } public static Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse2( final Response<AnalyzeTextTaskResult> response) { final KeyPhraseResult keyPhraseResult = ((KeyPhraseTaskResult) response.getValue()).getResults(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (KeyPhraseResultDocumentsItem 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 -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } public static RecognizeEntitiesResultCollection toRecognizeEntitiesResultCollectionResponse( final EntitiesResult entitiesResult) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); entitiesResult.getDocuments().forEach(documentEntities -> recognizeEntitiesResults.add(toRecognizeEntitiesResult(documentEntities))); for (DocumentError documentError : entitiesResult.getErrors()) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null : toBatchStatistics(entitiesResult.getStatistics())); } public static Response<RecognizeEntitiesResultCollection> toRecognizeEntitiesResultCollection( final Response<EntitiesResult> response) { EntitiesResult entitiesResult = response.getValue(); return new SimpleResponse<>(response, new RecognizeEntitiesResultCollection( toRecognizeEntitiesResults(entitiesResult), entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null : toBatchStatistics(entitiesResult.getStatistics()))); } public static Response<RecognizeEntitiesResultCollection> toRecognizeEntitiesResultCollection2( final Response<AnalyzeTextTaskResult> response) { EntitiesTaskResult entitiesTaskResult = (EntitiesTaskResult) response.getValue(); final EntitiesResult results = entitiesTaskResult.getResults(); return new SimpleResponse<>(response, new RecognizeEntitiesResultCollection( toRecognizeEntitiesResults(results), results.getModelVersion(), results.getStatistics() == null ? null : toBatchStatistics(results.getStatistics()))); } public static List<RecognizeEntitiesResult> toRecognizeEntitiesResults(EntitiesResult results) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); results.getDocuments().forEach( documentEntities -> recognizeEntitiesResults.add(new RecognizeEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new CategorizedEntityCollection( new IterableStream<>(documentEntities.getEntities().stream().map(entity -> { final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(), entity.getConfidenceScore()); CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength()); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity, entity.getOffset()); return categorizedEntity; }).collect(Collectors.toList())), new IterableStream<>( documentEntities.getWarnings().stream() .map(warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))))); for (DocumentError documentError : results.getErrors()) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return recognizeEntitiesResults; } public static RecognizeEntitiesResult toRecognizeEntitiesResult(EntitiesResultDocumentsItem documentEntities) { return new RecognizeEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new CategorizedEntityCollection( new IterableStream<>(documentEntities.getEntities().stream().map(entity -> { final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(), entity.getConfidenceScore()); CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength()); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity, entity.getOffset()); return categorizedEntity; }).collect(Collectors.toList())), new IterableStream<>(documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))); } public static RecognizeEntitiesResult toRecognizeEntitiesResult(CustomEntitiesResultDocumentsItem documentEntities) { return new RecognizeEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new CategorizedEntityCollection( new IterableStream<>(documentEntities.getEntities().stream().map(entity -> { final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(), entity.getConfidenceScore()); CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength()); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity, entity.getOffset()); return categorizedEntity; }).collect(Collectors.toList())), new IterableStream<>(documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))); } public static Response<RecognizePiiEntitiesResultCollection> toRecognizePiiEntitiesResultCollectionResponse( final Response<PiiResult> response) { final PiiResult piiEntitiesResult = response.getValue(); return new SimpleResponse<>(response, new RecognizePiiEntitiesResultCollection( toRecognizePiiEntitiesResults(piiEntitiesResult), piiEntitiesResult.getModelVersion(), piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics()) )); } public static Response<RecognizePiiEntitiesResultCollection> toRecognizePiiEntitiesResultCollectionResponse2( final Response<AnalyzeTextTaskResult> response) { final PiiResult piiEntitiesResult = ((PiiTaskResult) response.getValue()).getResults(); return new SimpleResponse<>(response, new RecognizePiiEntitiesResultCollection( toRecognizePiiEntitiesResults(piiEntitiesResult), piiEntitiesResult.getModelVersion(), piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics()) )); } public static List<RecognizePiiEntitiesResult> toRecognizePiiEntitiesResults(PiiResult piiEntitiesResult) { final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); piiEntitiesResult.getDocuments().forEach(documentEntities -> { final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map( entity -> { final PiiEntity piiEntity = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity, entity.getText()); PiiEntityPropertiesHelper.setCategory(piiEntity, PiiEntityCategory.fromString(entity.getCategory())); PiiEntityPropertiesHelper.setSubcategory(piiEntity, entity.getSubcategory()); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity, entity.getConfidenceScore()); PiiEntityPropertiesHelper.setOffset(piiEntity, entity.getOffset()); PiiEntityPropertiesHelper.setLength(piiEntity, entity.getLength()); return piiEntity; }) .collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); recognizeEntitiesResults.add(new RecognizePiiEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(), new IterableStream<>(warnings)) )); }); for (DocumentError documentError : piiEntitiesResult.getErrors()) { recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return recognizeEntitiesResults; } public static RecognizeEntitiesResult toRecognizeEntitiesResult(DocumentEntities documentEntities) { return new RecognizeEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new CategorizedEntityCollection( new IterableStream<>(documentEntities.getEntities().stream().map(entity -> { final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(), entity.getConfidenceScore()); CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength()); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity, entity.getOffset()); return categorizedEntity; }).collect(Collectors.toList())), new IterableStream<>(documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))); } public static RecognizePiiEntitiesResultCollection toRecognizePiiEntitiesResultCollection( final PiiResult piiEntitiesResult) { final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); piiEntitiesResult.getDocuments().forEach(documentEntities -> { final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity -> { final PiiEntity piiEntity = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity, entity.getText()); PiiEntityPropertiesHelper.setCategory(piiEntity, PiiEntityCategory.fromString(entity.getCategory())); PiiEntityPropertiesHelper.setSubcategory(piiEntity, entity.getSubcategory()); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity, entity.getConfidenceScore()); PiiEntityPropertiesHelper.setOffset(piiEntity, entity.getOffset()); return piiEntity; }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); recognizeEntitiesResults.add(new RecognizePiiEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(), new IterableStream<>(warnings)) )); }); for (DocumentError documentError : piiEntitiesResult.getErrors()) { recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(), piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics())); } public static ExtractKeyPhrasesResultCollection toExtractKeyPhrasesResultCollection( final KeyPhraseResult keyPhraseResult) { final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (KeyPhraseResultDocumentsItem 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 -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics())); } public static Response<RecognizeLinkedEntitiesResultCollection> toRecognizeLinkedEntitiesResultCollectionResponse( final Response<EntityLinkingResult> response) { final EntityLinkingResult entityLinkingResult = response.getValue(); return new SimpleResponse<>(response, new RecognizeLinkedEntitiesResultCollection(toRecognizeLinkedEntitiesResultCollection(entityLinkingResult), entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null : toBatchStatistics(entityLinkingResult.getStatistics()))); } public static Response<RecognizeLinkedEntitiesResultCollection> toRecognizeLinkedEntitiesResultCollection( final Response<AnalyzeTextTaskResult> response) { final EntityLinkingResult entityLinkingResult = ((EntityLinkingTaskResult) response.getValue()).getResults(); return new SimpleResponse<>(response, new RecognizeLinkedEntitiesResultCollection(toRecognizeLinkedEntitiesResultCollection(entityLinkingResult), entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null : toBatchStatistics(entityLinkingResult.getStatistics()))); } public static RecognizeLinkedEntitiesResultCollection toRecognizeLinkedEntitiesResultCollection( final EntityLinkingResult entityLinkingResult) { final List<RecognizeLinkedEntitiesResult> linkedEntitiesResults = entityLinkingResult.getDocuments().stream().map( documentLinkedEntities -> new RecognizeLinkedEntitiesResult( documentLinkedEntities.getId(), documentLinkedEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentLinkedEntities.getStatistics()), null, new LinkedEntityCollection(new IterableStream<>( documentLinkedEntities.getEntities().stream().map( linkedEntity -> { final LinkedEntity entity = new LinkedEntity( linkedEntity.getName(), new IterableStream<>( linkedEntity.getMatches().stream().map( match -> { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch( match.getText(), match.getConfidenceScore()); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, match.getOffset()); LinkedEntityMatchPropertiesHelper.setLength(linkedEntityMatch, match.getLength()); return linkedEntityMatch; }).collect(Collectors.toList())), linkedEntity.getLanguage(), linkedEntity.getId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(entity, linkedEntity.getBingId()); return entity; }).collect(Collectors.toList())), new IterableStream<>(documentLinkedEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))) ).collect(Collectors.toList()); for (DocumentError documentError : entityLinkingResult.getErrors()) { linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new RecognizeLinkedEntitiesResultCollection(linkedEntitiesResults, entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null : toBatchStatistics(entityLinkingResult.getStatistics())); } /** * Helper method to convert {@link SentimentResponse} to {@link AnalyzeSentimentResultCollection}. * * @param sentimentResponse The {@link SentimentResponse}. * * @return A {@link AnalyzeSentimentResultCollection}. */ public static AnalyzeSentimentResultCollection toAnalyzeSentimentResultCollection( SentimentResponse sentimentResponse) { final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); final List<SentimentResponseDocumentsItem> documentSentiments = sentimentResponse.getDocuments(); for (SentimentResponseDocumentsItem documentSentiment : documentSentiments) { analyzeSentimentResults.add(toAnalyzeSentimentResult(documentSentiment, documentSentiments)); } for (DocumentError documentError : sentimentResponse.getErrors()) { analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics())); } /** * Helper method to convert {@link ExtractiveSummarizationResult} to {@link ExtractSummaryResultCollection}. * * @param extractiveSummarizationResult The {@link ExtractiveSummarizationResult}. * * @return A {@link ExtractSummaryResultCollection}. */ public static ExtractSummaryResultCollection toExtractSummaryResultCollection( ExtractiveSummarizationResult extractiveSummarizationResult) { final List<ExtractSummaryResult> extractSummaryResults = new ArrayList<>(); final List<ExtractiveSummarizationResultDocumentsItem> extractedDocumentSummaries = extractiveSummarizationResult.getDocuments(); for (ExtractiveSummarizationResultDocumentsItem documentSummary : extractedDocumentSummaries) { extractSummaryResults.add(toExtractSummaryResult(documentSummary)); } for (DocumentError documentError : extractiveSummarizationResult.getErrors()) { extractSummaryResults.add(new ExtractSummaryResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()))); } return new ExtractSummaryResultCollection(extractSummaryResults, extractiveSummarizationResult.getModelVersion(), extractiveSummarizationResult.getStatistics() == null ? null : toBatchStatistics(extractiveSummarizationResult.getStatistics())); } /** * Transfer {@link HealthcareResult} into {@link AnalyzeHealthcareEntitiesResultCollection}. * * @param healthcareResult the service side raw data, HealthcareResult. * * @return the client side explored model, AnalyzeHealthcareEntitiesResultCollection. */ public static AnalyzeHealthcareEntitiesResultCollection toAnalyzeHealthcareEntitiesResultCollection( HealthcareResult healthcareResult) { List<AnalyzeHealthcareEntitiesResult> analyzeHealthcareEntitiesResults = new ArrayList<>(); healthcareResult.getDocuments().forEach( documentEntities -> { final AnalyzeHealthcareEntitiesResult analyzeHealthcareEntitiesResult = new AnalyzeHealthcareEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null); final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map( textAnalyticsWarning -> new TextAnalyticsWarning( Optional.ofNullable(textAnalyticsWarning.getCode()) .map(warningCodeValue -> WarningCode.fromString(warningCodeValue.toString())) .orElse(null), textAnalyticsWarning.getMessage()) ).collect(Collectors.toList()); AnalyzeHealthcareEntitiesResultPropertiesHelper.setWarnings(analyzeHealthcareEntitiesResult, IterableStream.of(warnings)); final List<HealthcareEntity> healthcareEntities = documentEntities.getEntities().stream().map( entity -> { final HealthcareEntity healthcareEntity = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity, entity.getText()); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity, entity.getName()); if (entity.getCategory() != null) { HealthcareEntityPropertiesHelper.setCategory(healthcareEntity, HealthcareEntityCategory.fromString(entity.getCategory().toString())); } HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity, entity.getConfidenceScore()); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity, entity.getOffset()); HealthcareEntityPropertiesHelper.setLength(healthcareEntity, entity.getLength()); final List<EntityDataSource> entityDataSources = Optional.ofNullable(entity.getLinks()).map( links -> links.stream().map( link -> { final EntityDataSource dataSource = new EntityDataSource(); EntityDataSourcePropertiesHelper.setName(dataSource, link.getDataSource()); EntityDataSourcePropertiesHelper.setEntityId(dataSource, link.getId()); return dataSource; } ).collect(Collectors.toList())) .orElse(new ArrayList<>()); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity, IterableStream.of(entityDataSources)); final HealthcareAssertion assertion = entity.getAssertion(); if (assertion != null) { HealthcareEntityPropertiesHelper.setAssertion(healthcareEntity, toHealthcareEntityAssertion(assertion)); } return healthcareEntity; }).collect(Collectors.toList()); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(analyzeHealthcareEntitiesResult, IterableStream.of(healthcareEntities)); final List<HealthcareEntityRelation> healthcareEntityRelations = documentEntities.getRelations().stream().map( healthcareRelation -> { final HealthcareEntityRelation entityRelation = new HealthcareEntityRelation(); final RelationType relationType = healthcareRelation.getRelationType(); if (relationType != null) { HealthcareEntityRelationPropertiesHelper.setRelationType(entityRelation, HealthcareEntityRelationType.fromString(relationType.toString())); } final List<HealthcareEntityRelationRole> relationRoles = healthcareRelation.getEntities().stream().map( relationEntity -> { final HealthcareEntityRelationRole relationRole = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(relationRole, relationEntity.getRole()); HealthcareEntityRelationRolePropertiesHelper.setEntity(relationRole, healthcareEntities.get(getHealthcareEntityIndex(relationEntity.getRef()))); return relationRole; }).collect(Collectors.toList()); HealthcareEntityRelationPropertiesHelper.setRoles(entityRelation, IterableStream.of(relationRoles)); return entityRelation; }).collect(Collectors.toList()); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(analyzeHealthcareEntitiesResult, IterableStream.of(healthcareEntityRelations)); analyzeHealthcareEntitiesResults.add(analyzeHealthcareEntitiesResult); }); healthcareResult.getErrors().forEach(documentError -> analyzeHealthcareEntitiesResults.add(new AnalyzeHealthcareEntitiesResult( documentError.getId(), null, toTextAnalyticsError(documentError.getError()))) ); return new AnalyzeHealthcareEntitiesResultCollection(IterableStream.of(analyzeHealthcareEntitiesResults)); } public static HealthcareEntityAssertion toHealthcareEntityAssertion(HealthcareAssertion healthcareAssertion) { final Association association = healthcareAssertion.getAssociation(); final Certainty certainty = healthcareAssertion.getCertainty(); final Conditionality conditionality = healthcareAssertion.getConditionality(); final HealthcareEntityAssertion entityAssertion = new HealthcareEntityAssertion(); if (association != null) { HealthcareEntityAssertionPropertiesHelper.setAssociation(entityAssertion, EntityAssociation.fromString(association.toString())); } if (certainty != null) { HealthcareEntityAssertionPropertiesHelper.setCertainty(entityAssertion, toCertainty(certainty)); } if (conditionality != null) { HealthcareEntityAssertionPropertiesHelper.setConditionality(entityAssertion, toConditionality(conditionality)); } return entityAssertion; } private static EntityCertainty toCertainty(Certainty certainty) { EntityCertainty entityCertainty1 = null; switch (certainty) { case POSITIVE: entityCertainty1 = EntityCertainty.POSITIVE; break; case POSITIVE_POSSIBLE: entityCertainty1 = EntityCertainty.POSITIVE_POSSIBLE; break; case NEUTRAL_POSSIBLE: entityCertainty1 = EntityCertainty.NEUTRAL_POSSIBLE; break; case NEGATIVE_POSSIBLE: entityCertainty1 = EntityCertainty.NEGATIVE_POSSIBLE; break; case NEGATIVE: entityCertainty1 = EntityCertainty.NEGATIVE; break; default: break; } return entityCertainty1; } private static EntityConditionality toConditionality(Conditionality conditionality) { EntityConditionality conditionality1 = null; switch (conditionality) { case HYPOTHETICAL: conditionality1 = EntityConditionality.HYPOTHETICAL; break; case CONDITIONAL: conditionality1 = EntityConditionality.CONDITIONAL; break; default: break; } return conditionality1; } /** * Helper function that parse healthcare entity index from the given entity reference string. * The entity reference format is " * * @param entityReference the given healthcare entity reference string. * * @return the healthcare entity index. */ private static Integer getHealthcareEntityIndex(String entityReference) { if (!CoreUtils.isNullOrEmpty(entityReference)) { int lastIndex = entityReference.lastIndexOf('/'); if (lastIndex != -1) { return Integer.parseInt(entityReference.substring(lastIndex + 1)); } } throw LOGGER.logExceptionAsError( new RuntimeException("Failed to parse healthcare entity index from: " + entityReference)); } /** * Get the non-null {@link Context}. The default value is {@link Context * * @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies. * Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null. * * @return The Context. */ public static Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } /** * Helper function which retrieves the size of an {@link Iterable}. * * @param documents The iterable of documents. * @return Count of documents in the iterable. */ public static int getDocumentCount(Iterable<?> documents) { if (documents instanceof Collection) { return ((Collection<?>) documents).size(); } else { final int[] count = new int[] { 0 }; documents.forEach(ignored -> count[0] += 1); return count[0]; } } /** * Helper function which convert the {@code Iterable<PiiEntityCategory>} to {@code List<PiiCategory>}. * * @param categoriesFilter the iterable of {@link PiiEntityCategory}. * @return the list of {@link PiiCategory}. */ public static List<PiiCategory> toCategoriesFilter(Iterable<PiiEntityCategory> categoriesFilter) { if (categoriesFilter == null) { return null; } final List<PiiCategory> piiCategories = new ArrayList<>(); categoriesFilter.forEach(category -> piiCategories.add(PiiCategory.fromString(category.toString()))); return piiCategories; } /** * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. * * @param documentSentiment The {@link SentimentResponseDocumentsItem} returned by the service. * @param documentSentimentList The document sentiment list returned by the service. * * @return The {@link AnalyzeSentimentResult} to be returned by the SDK. */ private static AnalyzeSentimentResult toAnalyzeSentimentResult(SentimentResponseDocumentsItem documentSentiment, List<SentimentResponseDocumentsItem> documentSentimentList) { final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores(); final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream() .map(sentenceSentiment -> { final SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getConfidenceScores(); final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment(); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment(sentenceSentiment.getText(), TextSentiment.fromString(sentenceSentimentValue == null ? null : sentenceSentimentValue.toString()), new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(), confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive())); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, toSentenceOpinionList(sentenceSentiment, documentSentimentList)); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, sentenceSentiment.getOffset()); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, sentenceSentiment.getLength()); return sentenceSentiment1; }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment(); return new AnalyzeSentimentResult( documentSentiment.getId(), documentSentiment.getStatistics() == null ? null : toTextDocumentStatistics(documentSentiment.getStatistics()), null, new com.azure.ai.textanalytics.models.DocumentSentiment( TextSentiment.fromString(documentSentimentValue == null ? null : documentSentimentValue.toString()), new SentimentConfidenceScores( confidenceScorePerLabel.getNegative(), confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive()), new IterableStream<>(sentenceSentiments), new IterableStream<>(warnings) )); } /* * Transform SentenceSentiment's opinion mining to output that user can use. */ private static IterableStream<SentenceOpinion> toSentenceOpinionList( com.azure.ai.textanalytics.implementation.models.SentenceSentiment sentenceSentiment, List<SentimentResponseDocumentsItem> documentSentimentList) { final List<SentenceTarget> sentenceTargets = sentenceSentiment.getTargets(); if (sentenceTargets == null) { return null; } final List<SentenceOpinion> sentenceOpinions = new ArrayList<>(); sentenceTargets.forEach(sentenceTarget -> { final List<AssessmentSentiment> assessmentSentiments = new ArrayList<>(); sentenceTarget.getRelations().forEach(targetRelation -> { final TargetRelationType targetRelationType = targetRelation.getRelationType(); final String opinionPointer = targetRelation.getRef(); if (TargetRelationType.ASSESSMENT == targetRelationType) { assessmentSentiments.add(toAssessmentSentiment( findSentimentAssessment(opinionPointer, documentSentimentList))); } }); final TargetSentiment targetSentiment = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment, sentenceTarget.getText()); TargetSentimentPropertiesHelper.setSentiment(targetSentiment, TextSentiment.fromString(sentenceTarget.getSentiment().toString())); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment, toSentimentConfidenceScores(sentenceTarget.getConfidenceScores())); TargetSentimentPropertiesHelper.setOffset(targetSentiment, sentenceTarget.getOffset()); TargetSentimentPropertiesHelper.setLength(targetSentiment, sentenceTarget.getLength()); final SentenceOpinion sentenceOpinion = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion, targetSentiment); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion, new IterableStream<>(assessmentSentiments)); sentenceOpinions.add(sentenceOpinion); }); return new IterableStream<>(sentenceOpinions); } /* * Transform type TargetConfidenceScoreLabel to SentimentConfidenceScores. */ private static SentimentConfidenceScores toSentimentConfidenceScores( TargetConfidenceScoreLabel targetConfidenceScoreLabel) { return new SentimentConfidenceScores(targetConfidenceScoreLabel.getNegative(), NEUTRAL_SCORE_ZERO, targetConfidenceScoreLabel.getPositive()); } /* * Transform type SentenceOpinion to OpinionSentiment. */ private static AssessmentSentiment toAssessmentSentiment(SentenceAssessment sentenceAssessment) { final AssessmentSentiment assessmentSentiment = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment, sentenceAssessment.getText()); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment, TextSentiment.fromString(sentenceAssessment.getSentiment().toString())); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment, toSentimentConfidenceScores(sentenceAssessment.getConfidenceScores())); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment, sentenceAssessment.isNegated()); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment, sentenceAssessment.getOffset()); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment, sentenceAssessment.getLength()); return assessmentSentiment; } private static ExtractSummaryResult toExtractSummaryResult( ExtractiveSummarizationResultDocumentsItem documentSummary) { final List<ExtractedSummarySentence> sentences = documentSummary.getSentences(); final List<SummarySentence> summarySentences = sentences.stream().map(sentence -> { final SummarySentence summarySentence = new SummarySentence(); SummarySentencePropertiesHelper.setText(summarySentence, sentence.getText()); SummarySentencePropertiesHelper.setRankScore(summarySentence, sentence.getRankScore()); SummarySentencePropertiesHelper.setLength(summarySentence, sentence.getLength()); SummarySentencePropertiesHelper.setOffset(summarySentence, sentence.getOffset()); return summarySentence; }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSummary.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); final SummarySentenceCollection summarySentenceCollection = new SummarySentenceCollection( new IterableStream<>(summarySentences), new IterableStream<>(warnings) ); final ExtractSummaryResult extractSummaryResult = new ExtractSummaryResult(documentSummary.getId(), documentSummary.getStatistics() == null ? null : toTextDocumentStatistics(documentSummary.getStatistics()), null ); ExtractSummaryResultPropertiesHelper.setSentences(extractSummaryResult, summarySentenceCollection); return extractSummaryResult; } /** * Helper method to convert {@link CustomEntitiesResult} to {@link RecognizeCustomEntitiesResultCollection}. * * @param customEntitiesResult The {@link CustomEntitiesResult}. * * @return A {@link RecognizeCustomEntitiesResultCollection}. */ public static RecognizeCustomEntitiesResultCollection toRecognizeCustomEntitiesResultCollection( CustomEntitiesResult customEntitiesResult) { final List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); final List<CustomEntitiesResultDocumentsItem> customEntitiesResultDocuments = customEntitiesResult.getDocuments(); for (CustomEntitiesResultDocumentsItem documentSummary : customEntitiesResultDocuments) { recognizeEntitiesResults.add(toRecognizeEntitiesResult(documentSummary)); } for (DocumentError documentError : customEntitiesResult.getErrors()) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } final RecognizeCustomEntitiesResultCollection resultCollection = new RecognizeCustomEntitiesResultCollection(recognizeEntitiesResults); RecognizeCustomEntitiesResultCollectionPropertiesHelper.setProjectName(resultCollection, customEntitiesResult.getProjectName()); RecognizeCustomEntitiesResultCollectionPropertiesHelper.setDeploymentName(resultCollection, customEntitiesResult.getDeploymentName()); if (customEntitiesResult.getStatistics() != null) { RecognizeCustomEntitiesResultCollectionPropertiesHelper.setStatistics(resultCollection, toBatchStatistics(customEntitiesResult.getStatistics())); } return resultCollection; } /** * Helper method to convert {@link CustomSingleClassificationResult} to * {@link SingleCategoryClassifyResultCollection}. * * @param customSingleClassificationResult The {@link CustomSingleClassificationResult}. * * @return A {@link SingleCategoryClassifyResultCollection}. */ public static SingleCategoryClassifyResultCollection toSingleCategoryClassifyResultCollection( CustomSingleLabelClassificationResult customSingleClassificationResult) { final List<SingleCategoryClassifyResult> singleCategoryClassifyResults = new ArrayList<>(); final List<CustomSingleLabelClassificationResultDocumentsItem> singleClassificationDocuments = customSingleClassificationResult.getDocuments(); for (CustomSingleLabelClassificationResultDocumentsItem documentSummary : singleClassificationDocuments) { singleCategoryClassifyResults.add(toSingleCategoryClassifyResult(documentSummary)); } for (DocumentError documentError : customSingleClassificationResult.getErrors()) { singleCategoryClassifyResults.add(new SingleCategoryClassifyResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()))); } final SingleCategoryClassifyResultCollection resultCollection = new SingleCategoryClassifyResultCollection(singleCategoryClassifyResults); SingleCategoryClassifyResultCollectionPropertiesHelper.setProjectName(resultCollection, customSingleClassificationResult.getProjectName()); SingleCategoryClassifyResultCollectionPropertiesHelper.setDeploymentName(resultCollection, customSingleClassificationResult.getDeploymentName()); if (customSingleClassificationResult.getStatistics() != null) { SingleCategoryClassifyResultCollectionPropertiesHelper.setStatistics(resultCollection, toBatchStatistics(customSingleClassificationResult.getStatistics())); } return resultCollection; } private static SingleCategoryClassifyResult toSingleCategoryClassifyResult( CustomSingleLabelClassificationResultDocumentsItem singleClassificationDocument) { final ClassificationResult classificationResult = singleClassificationDocument.getClassProperty(); final List<TextAnalyticsWarning> warnings = singleClassificationDocument.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); final SingleCategoryClassifyResult singleCategoryClassifyResult = new SingleCategoryClassifyResult( singleClassificationDocument.getId(), singleClassificationDocument.getStatistics() == null ? null : toTextDocumentStatistics(singleClassificationDocument.getStatistics()), null); SingleCategoryClassifyResultPropertiesHelper.setClassification(singleCategoryClassifyResult, toDocumentClassification(classificationResult)); SingleCategoryClassifyResultPropertiesHelper.setWarnings(singleCategoryClassifyResult, new IterableStream<>(warnings)); return singleCategoryClassifyResult; } private static ClassificationCategory toDocumentClassification(ClassificationResult classificationResult) { final ClassificationCategory classificationCategory = new ClassificationCategory(); ClassificationCategoryPropertiesHelper.setCategory(classificationCategory, classificationResult.getCategory()); ClassificationCategoryPropertiesHelper.setConfidenceScore(classificationCategory, classificationResult.getConfidenceScore()); return classificationCategory; } /** * Helper method to convert {@link CustomMultiClassificationResult} to * {@link MultiCategoryClassifyResultCollection}. * * @param customMultiClassificationResult The {@link CustomMultiClassificationResult}. * * @return A {@link SingleCategoryClassifyResultCollection}. */ public static MultiCategoryClassifyResultCollection toMultiCategoryClassifyResultCollection( CustomMultiLabelClassificationResult customMultiClassificationResult) { final List<MultiCategoryClassifyResult> multiCategoryClassifyResults = new ArrayList<>(); final List<CustomMultiLabelClassificationResultDocumentsItem> multiClassificationDocuments = customMultiClassificationResult.getDocuments(); for (CustomMultiLabelClassificationResultDocumentsItem multiClassificationDocument : multiClassificationDocuments) { multiCategoryClassifyResults.add(toMultiCategoryClassifyResult(multiClassificationDocument)); } for (DocumentError documentError : customMultiClassificationResult.getErrors()) { multiCategoryClassifyResults.add(new MultiCategoryClassifyResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()))); } final MultiCategoryClassifyResultCollection resultCollection = new MultiCategoryClassifyResultCollection(multiCategoryClassifyResults); MultiCategoryClassifyResultCollectionPropertiesHelper.setProjectName(resultCollection, customMultiClassificationResult.getProjectName()); MultiCategoryClassifyResultCollectionPropertiesHelper.setDeploymentName(resultCollection, customMultiClassificationResult.getDeploymentName()); if (customMultiClassificationResult.getStatistics() != null) { MultiCategoryClassifyResultCollectionPropertiesHelper.setStatistics(resultCollection, toBatchStatistics(customMultiClassificationResult.getStatistics())); } return resultCollection; } private static MultiCategoryClassifyResult toMultiCategoryClassifyResult( CustomMultiLabelClassificationResultDocumentsItem multiClassificationDocument) { final List<ClassificationCategory> classificationCategories = multiClassificationDocument .getClassProperty() .stream() .map(classificationResult -> toDocumentClassification(classificationResult)) .collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = multiClassificationDocument.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); final MultiCategoryClassifyResult classifySingleCategoryResult = new MultiCategoryClassifyResult( multiClassificationDocument.getId(), multiClassificationDocument.getStatistics() == null ? null : toTextDocumentStatistics(multiClassificationDocument.getStatistics()), null); final ClassificationCategoryCollection classifications = new ClassificationCategoryCollection( new IterableStream<>(classificationCategories)); ClassificationCategoryCollectionPropertiesHelper.setWarnings(classifications, new IterableStream<>(warnings)); MultiCategoryClassifyResultPropertiesHelper.setClassifications(classifySingleCategoryResult, classifications); return classifySingleCategoryResult; } /* * Parses the reference pointer to an index array that contains document, sentence, and opinion indexes. */ public static int[] parseRefPointerToIndexArray(String assessmentPointer) { final Matcher matcher = PATTERN.matcher(assessmentPointer); final boolean isMatched = matcher.find(); final int[] result = new int[3]; if (isMatched) { result[0] = Integer.parseInt(matcher.group(1)); result[1] = Integer.parseInt(matcher.group(2)); result[2] = Integer.parseInt(matcher.group(3)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( String.format("'%s' is not a valid assessment pointer.", assessmentPointer))); } return result; } /* * Find the specific sentence assessment in the document sentiment list by given the assessment reference pointer. */ public static SentenceAssessment findSentimentAssessment(String assessmentPointer, List<SentimentResponseDocumentsItem> documentSentiments) { final int[] assessmentIndexes = parseRefPointerToIndexArray(assessmentPointer); final int documentIndex = assessmentIndexes[0]; final int sentenceIndex = assessmentIndexes[1]; final int assessmentIndex = assessmentIndexes[2]; if (documentIndex >= documentSentiments.size()) { throw LOGGER.logExceptionAsError(new IllegalStateException( String.format("Invalid document index '%s' in '%s'.", documentIndex, assessmentPointer))); } final SentimentResponseDocumentsItem documentsentiment = documentSentiments.get(documentIndex); final List<com.azure.ai.textanalytics.implementation.models.SentenceSentiment> sentenceSentiments = documentsentiment.getSentences(); if (sentenceIndex >= sentenceSentiments.size()) { throw LOGGER.logExceptionAsError(new IllegalStateException( String.format("Invalid sentence index '%s' in '%s'.", sentenceIndex, assessmentPointer))); } final List<SentenceAssessment> assessments = sentenceSentiments.get(sentenceIndex).getAssessments(); if (assessmentIndex >= assessments.size()) { throw LOGGER.logExceptionAsError(new IllegalStateException( String.format("Invalid assessment index '%s' in '%s'.", assessmentIndex, assessmentPointer))); } return assessments.get(assessmentIndex); } }
class Utility { public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(30); private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final int NEUTRAL_SCORE_ZERO = 0; private static final int OPERATION_ID_LENGTH = 37; private static final String DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP = " private static final Pattern PATTERN; static { PATTERN = Pattern.compile(DOCUMENT_SENTENCES_ASSESSMENTS_REG_EXP); } private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is null. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Mapping a {@link ErrorResponseException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ public static Throwable mapToHttpResponseExceptionIfExists(Throwable throwable) { if (throwable instanceof ErrorResponseException) { ErrorResponseException errorException = (ErrorResponseException) throwable; final ErrorResponse errorResponse = errorException.getValue(); com.azure.ai.textanalytics.models.TextAnalyticsError textAnalyticsError = null; if (errorResponse != null && errorResponse.getError() != null) { textAnalyticsError = toTextAnalyticsError(errorResponse.getError()); } return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), textAnalyticsError); } return throwable; } /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link Error} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link Error inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param error the {@link Error} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static TextAnalyticsError toTextAnalyticsError(Error error) { final InnerErrorModel innerError = error.getInnererror(); if (innerError == null) { final ErrorCode errorCode = error.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCode == null ? null : errorCode.toString()), error.getMessage(), error.getTarget()); } final InnerErrorCode innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } public static TextAnalyticsWarning toTextAnalyticsWarning( DocumentWarning warning) { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning( WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()), warning.getMessage()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } /** * Extracts the operation ID from the 'operation-location' URL. An example of 'operation-location' is * https: * * @param operationLocation The URL specified in the 'Operation-Location' response header containing the * operation ID used to track the progress and obtain the ID of the analyze operation. * * @return The operation ID that tracks the long running operation progress. */ /** * Extract the next pagination link which contains the request parameter values, into map, * such as '$skip=20' and '$top=2'. * * @param nextLink the next pagination link. * * @return A map that holds the request parameter value of next pagination link. */ public static Map<String, Object> parseNextLink(String nextLink) { if (!CoreUtils.isNullOrEmpty(nextLink)) { final Map<String, Object> parameterMap = new HashMap<>(); final String[] strings = nextLink.split("\\?", 2); final String[] parameters = strings[1].split("&"); for (String parameter : parameters) { final String[] parameterPair = parameter.split("="); final String key = parameterPair[0]; final String value = parameterPair[1]; if ("showStats".equals(key)) { parameterMap.put(key, value); } else if ("$skip".equals(key) || "$top".equals(key)) { parameterMap.put(key, Integer.valueOf(value)); } else if ("skip".equals(key) || "top".equals(key)) { parameterMap.put("$" + key, Integer.valueOf(value)); } } return parameterMap; } return new HashMap<>(); } public static Response<AnalyzeSentimentResultCollection> toAnalyzeSentimentResultCollectionResponse( Response<SentimentResponse> response) { return new SimpleResponse<>(response, toAnalyzeSentimentResultCollection(response.getValue())); } public static Response<AnalyzeSentimentResultCollection> toAnalyzeSentimentResultCollectionResponse2( Response<AnalyzeTextTaskResult> response) { return new SimpleResponse<>(response, toAnalyzeSentimentResultCollection(((SentimentTaskResult) response.getValue()).getResults())); } public static Response<DetectLanguageResultCollection> toDetectLanguageResultCollectionResponse( Response<LanguageResult> response) { final LanguageResult languageResult = response.getValue(); final List<DetectLanguageResult> detectLanguageResults = new ArrayList<>(); for (DocumentLanguage documentLanguage : languageResult.getDocuments()) { com.azure.ai.textanalytics.implementation.models.DetectedLanguage detectedLanguage = documentLanguage.getDetectedLanguage(); final List<TextAnalyticsWarning> warnings = documentLanguage.getWarnings().stream() .map(warning -> toTextAnalyticsWarning(warning)) .collect(Collectors.toList()); detectLanguageResults.add(new DetectLanguageResult( documentLanguage.getId(), documentLanguage.getStatistics() == null ? null : toTextDocumentStatistics(documentLanguage.getStatistics()), null, new DetectedLanguage(detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore(), new IterableStream<>(warnings)))); } for (DocumentError documentError : languageResult.getErrors()) { detectLanguageResults.add(new DetectLanguageResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new DetectLanguageResultCollection(detectLanguageResults, languageResult.getModelVersion(), languageResult.getStatistics() == null ? null : toBatchStatistics(languageResult.getStatistics()))); } public static Response<DetectLanguageResultCollection> toDetectLanguageResultCollectionResponse2( Response<AnalyzeTextTaskResult> response) { final LanguageDetectionResult languageResult = ((LanguageDetectionTaskResult) response.getValue()).getResults(); final List<DetectLanguageResult> detectLanguageResults = new ArrayList<>(); for (LanguageDetectionDocumentResult documentLanguage : languageResult.getDocuments()) { com.azure.ai.textanalytics.implementation.models.DetectedLanguage detectedLanguage = documentLanguage.getDetectedLanguage(); final List<TextAnalyticsWarning> warnings = documentLanguage.getWarnings() .stream() .map(warning -> toTextAnalyticsWarning(warning)) .collect(Collectors.toList()); detectLanguageResults.add(new DetectLanguageResult( documentLanguage.getId(), documentLanguage.getStatistics() == null ? null : toTextDocumentStatistics(documentLanguage.getStatistics()), null, new DetectedLanguage(detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore(), new IterableStream<>(warnings) ))); } for (DocumentError documentError : languageResult.getErrors()) { detectLanguageResults.add(new DetectLanguageResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new DetectLanguageResultCollection(detectLanguageResults, languageResult.getModelVersion(), languageResult.getStatistics() == null ? null : toBatchStatistics(languageResult.getStatistics()))); } public static Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse( final Response<KeyPhraseResult> response) { final KeyPhraseResult keyPhraseResult = response.getValue(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (KeyPhraseResultDocumentsItem 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 -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } public static Response<ExtractKeyPhrasesResultCollection> toExtractKeyPhrasesResultCollectionResponse2( final Response<AnalyzeTextTaskResult> response) { final KeyPhraseResult keyPhraseResult = ((KeyPhraseTaskResult) response.getValue()).getResults(); final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (KeyPhraseResultDocumentsItem 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 -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics()))); } public static RecognizeEntitiesResultCollection toRecognizeEntitiesResultCollectionResponse( final EntitiesResult entitiesResult) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); entitiesResult.getDocuments().forEach(documentEntities -> recognizeEntitiesResults.add(toRecognizeEntitiesResult(documentEntities))); for (DocumentError documentError : entitiesResult.getErrors()) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null : toBatchStatistics(entitiesResult.getStatistics())); } public static Response<RecognizeEntitiesResultCollection> toRecognizeEntitiesResultCollection( final Response<EntitiesResult> response) { EntitiesResult entitiesResult = response.getValue(); return new SimpleResponse<>(response, new RecognizeEntitiesResultCollection( toRecognizeEntitiesResults(entitiesResult), entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null : toBatchStatistics(entitiesResult.getStatistics()))); } public static Response<RecognizeEntitiesResultCollection> toRecognizeEntitiesResultCollection2( final Response<AnalyzeTextTaskResult> response) { EntitiesTaskResult entitiesTaskResult = (EntitiesTaskResult) response.getValue(); final EntitiesResult results = entitiesTaskResult.getResults(); return new SimpleResponse<>(response, new RecognizeEntitiesResultCollection( toRecognizeEntitiesResults(results), results.getModelVersion(), results.getStatistics() == null ? null : toBatchStatistics(results.getStatistics()))); } public static List<RecognizeEntitiesResult> toRecognizeEntitiesResults(EntitiesResult results) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); results.getDocuments().forEach( documentEntities -> recognizeEntitiesResults.add(new RecognizeEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new CategorizedEntityCollection( new IterableStream<>(documentEntities.getEntities().stream().map(entity -> { final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(), entity.getConfidenceScore()); CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength()); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity, entity.getOffset()); return categorizedEntity; }).collect(Collectors.toList())), new IterableStream<>( documentEntities.getWarnings().stream() .map(warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))))); for (DocumentError documentError : results.getErrors()) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return recognizeEntitiesResults; } public static RecognizeEntitiesResult toRecognizeEntitiesResult(EntitiesResultDocumentsItem documentEntities) { return new RecognizeEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new CategorizedEntityCollection( new IterableStream<>(documentEntities.getEntities().stream().map(entity -> { final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(), entity.getConfidenceScore()); CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength()); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity, entity.getOffset()); return categorizedEntity; }).collect(Collectors.toList())), new IterableStream<>(documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))); } public static RecognizeEntitiesResult toRecognizeEntitiesResult(CustomEntitiesResultDocumentsItem documentEntities) { return new RecognizeEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new CategorizedEntityCollection( new IterableStream<>(documentEntities.getEntities().stream().map(entity -> { final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(), entity.getConfidenceScore()); CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength()); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity, entity.getOffset()); return categorizedEntity; }).collect(Collectors.toList())), new IterableStream<>(documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))); } public static Response<RecognizePiiEntitiesResultCollection> toRecognizePiiEntitiesResultCollectionResponse( final Response<PiiResult> response) { final PiiResult piiEntitiesResult = response.getValue(); return new SimpleResponse<>(response, new RecognizePiiEntitiesResultCollection( toRecognizePiiEntitiesResults(piiEntitiesResult), piiEntitiesResult.getModelVersion(), piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics()) )); } public static Response<RecognizePiiEntitiesResultCollection> toRecognizePiiEntitiesResultCollectionResponse2( final Response<AnalyzeTextTaskResult> response) { final PiiResult piiEntitiesResult = ((PiiTaskResult) response.getValue()).getResults(); return new SimpleResponse<>(response, new RecognizePiiEntitiesResultCollection( toRecognizePiiEntitiesResults(piiEntitiesResult), piiEntitiesResult.getModelVersion(), piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics()) )); } public static List<RecognizePiiEntitiesResult> toRecognizePiiEntitiesResults(PiiResult piiEntitiesResult) { final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); piiEntitiesResult.getDocuments().forEach(documentEntities -> { final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map( entity -> { final PiiEntity piiEntity = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity, entity.getText()); PiiEntityPropertiesHelper.setCategory(piiEntity, PiiEntityCategory.fromString(entity.getCategory())); PiiEntityPropertiesHelper.setSubcategory(piiEntity, entity.getSubcategory()); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity, entity.getConfidenceScore()); PiiEntityPropertiesHelper.setOffset(piiEntity, entity.getOffset()); PiiEntityPropertiesHelper.setLength(piiEntity, entity.getLength()); return piiEntity; }) .collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); recognizeEntitiesResults.add(new RecognizePiiEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(), new IterableStream<>(warnings)) )); }); for (DocumentError documentError : piiEntitiesResult.getErrors()) { recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return recognizeEntitiesResults; } public static RecognizeEntitiesResult toRecognizeEntitiesResult(DocumentEntities documentEntities) { return new RecognizeEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new CategorizedEntityCollection( new IterableStream<>(documentEntities.getEntities().stream().map(entity -> { final CategorizedEntity categorizedEntity = new CategorizedEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()), entity.getSubcategory(), entity.getConfidenceScore()); CategorizedEntityPropertiesHelper.setLength(categorizedEntity, entity.getLength()); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity, entity.getOffset()); return categorizedEntity; }).collect(Collectors.toList())), new IterableStream<>(documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))); } public static RecognizePiiEntitiesResultCollection toRecognizePiiEntitiesResultCollection( final PiiResult piiEntitiesResult) { final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); piiEntitiesResult.getDocuments().forEach(documentEntities -> { final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity -> { final PiiEntity piiEntity = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity, entity.getText()); PiiEntityPropertiesHelper.setCategory(piiEntity, PiiEntityCategory.fromString(entity.getCategory())); PiiEntityPropertiesHelper.setSubcategory(piiEntity, entity.getSubcategory()); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity, entity.getConfidenceScore()); PiiEntityPropertiesHelper.setOffset(piiEntity, entity.getOffset()); return piiEntity; }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); recognizeEntitiesResults.add(new RecognizePiiEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null, new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(), new IterableStream<>(warnings)) )); }); for (DocumentError documentError : piiEntitiesResult.getErrors()) { recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(), piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics())); } public static ExtractKeyPhrasesResultCollection toExtractKeyPhrasesResultCollection( final KeyPhraseResult keyPhraseResult) { final List<ExtractKeyPhraseResult> keyPhraseResultList = new ArrayList<>(); for (KeyPhraseResultDocumentsItem 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 -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()))))); } for (DocumentError documentError : keyPhraseResult.getErrors()) { keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new ExtractKeyPhrasesResultCollection(keyPhraseResultList, keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null : toBatchStatistics(keyPhraseResult.getStatistics())); } public static Response<RecognizeLinkedEntitiesResultCollection> toRecognizeLinkedEntitiesResultCollectionResponse( final Response<EntityLinkingResult> response) { final EntityLinkingResult entityLinkingResult = response.getValue(); return new SimpleResponse<>(response, new RecognizeLinkedEntitiesResultCollection(toRecognizeLinkedEntitiesResultCollection(entityLinkingResult), entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null : toBatchStatistics(entityLinkingResult.getStatistics()))); } public static Response<RecognizeLinkedEntitiesResultCollection> toRecognizeLinkedEntitiesResultCollection( final Response<AnalyzeTextTaskResult> response) { final EntityLinkingResult entityLinkingResult = ((EntityLinkingTaskResult) response.getValue()).getResults(); return new SimpleResponse<>(response, new RecognizeLinkedEntitiesResultCollection(toRecognizeLinkedEntitiesResultCollection(entityLinkingResult), entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null : toBatchStatistics(entityLinkingResult.getStatistics()))); } public static RecognizeLinkedEntitiesResultCollection toRecognizeLinkedEntitiesResultCollection( final EntityLinkingResult entityLinkingResult) { final List<RecognizeLinkedEntitiesResult> linkedEntitiesResults = entityLinkingResult.getDocuments().stream().map( documentLinkedEntities -> new RecognizeLinkedEntitiesResult( documentLinkedEntities.getId(), documentLinkedEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentLinkedEntities.getStatistics()), null, new LinkedEntityCollection(new IterableStream<>( documentLinkedEntities.getEntities().stream().map( linkedEntity -> { final LinkedEntity entity = new LinkedEntity( linkedEntity.getName(), new IterableStream<>( linkedEntity.getMatches().stream().map( match -> { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch( match.getText(), match.getConfidenceScore()); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, match.getOffset()); LinkedEntityMatchPropertiesHelper.setLength(linkedEntityMatch, match.getLength()); return linkedEntityMatch; }).collect(Collectors.toList())), linkedEntity.getLanguage(), linkedEntity.getId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(entity, linkedEntity.getBingId()); return entity; }).collect(Collectors.toList())), new IterableStream<>(documentLinkedEntities.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList())))) ).collect(Collectors.toList()); for (DocumentError documentError : entityLinkingResult.getErrors()) { linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new RecognizeLinkedEntitiesResultCollection(linkedEntitiesResults, entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null : toBatchStatistics(entityLinkingResult.getStatistics())); } /** * Helper method to convert {@link SentimentResponse} to {@link AnalyzeSentimentResultCollection}. * * @param sentimentResponse The {@link SentimentResponse}. * * @return A {@link AnalyzeSentimentResultCollection}. */ public static AnalyzeSentimentResultCollection toAnalyzeSentimentResultCollection( SentimentResponse sentimentResponse) { final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); final List<SentimentResponseDocumentsItem> documentSentiments = sentimentResponse.getDocuments(); for (SentimentResponseDocumentsItem documentSentiment : documentSentiments) { analyzeSentimentResults.add(toAnalyzeSentimentResult(documentSentiment, documentSentiments)); } for (DocumentError documentError : sentimentResponse.getErrors()) { analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics())); } /** * Helper method to convert {@link ExtractiveSummarizationResult} to {@link ExtractSummaryResultCollection}. * * @param extractiveSummarizationResult The {@link ExtractiveSummarizationResult}. * * @return A {@link ExtractSummaryResultCollection}. */ public static ExtractSummaryResultCollection toExtractSummaryResultCollection( ExtractiveSummarizationResult extractiveSummarizationResult) { final List<ExtractSummaryResult> extractSummaryResults = new ArrayList<>(); final List<ExtractiveSummarizationResultDocumentsItem> extractedDocumentSummaries = extractiveSummarizationResult.getDocuments(); for (ExtractiveSummarizationResultDocumentsItem documentSummary : extractedDocumentSummaries) { extractSummaryResults.add(toExtractSummaryResult(documentSummary)); } for (DocumentError documentError : extractiveSummarizationResult.getErrors()) { extractSummaryResults.add(new ExtractSummaryResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()))); } return new ExtractSummaryResultCollection(extractSummaryResults, extractiveSummarizationResult.getModelVersion(), extractiveSummarizationResult.getStatistics() == null ? null : toBatchStatistics(extractiveSummarizationResult.getStatistics())); } /** * Transfer {@link HealthcareResult} into {@link AnalyzeHealthcareEntitiesResultCollection}. * * @param healthcareResult the service side raw data, HealthcareResult. * * @return the client side explored model, AnalyzeHealthcareEntitiesResultCollection. */ public static AnalyzeHealthcareEntitiesResultCollection toAnalyzeHealthcareEntitiesResultCollection( HealthcareResult healthcareResult) { List<AnalyzeHealthcareEntitiesResult> analyzeHealthcareEntitiesResults = new ArrayList<>(); healthcareResult.getDocuments().forEach( documentEntities -> { final AnalyzeHealthcareEntitiesResult analyzeHealthcareEntitiesResult = new AnalyzeHealthcareEntitiesResult( documentEntities.getId(), documentEntities.getStatistics() == null ? null : toTextDocumentStatistics(documentEntities.getStatistics()), null); final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream().map( textAnalyticsWarning -> new TextAnalyticsWarning( Optional.ofNullable(textAnalyticsWarning.getCode()) .map(warningCodeValue -> WarningCode.fromString(warningCodeValue.toString())) .orElse(null), textAnalyticsWarning.getMessage()) ).collect(Collectors.toList()); AnalyzeHealthcareEntitiesResultPropertiesHelper.setWarnings(analyzeHealthcareEntitiesResult, IterableStream.of(warnings)); final List<HealthcareEntity> healthcareEntities = documentEntities.getEntities().stream().map( entity -> { final HealthcareEntity healthcareEntity = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity, entity.getText()); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity, entity.getName()); if (entity.getCategory() != null) { HealthcareEntityPropertiesHelper.setCategory(healthcareEntity, HealthcareEntityCategory.fromString(entity.getCategory().toString())); } HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity, entity.getConfidenceScore()); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity, entity.getOffset()); HealthcareEntityPropertiesHelper.setLength(healthcareEntity, entity.getLength()); final List<EntityDataSource> entityDataSources = Optional.ofNullable(entity.getLinks()).map( links -> links.stream().map( link -> { final EntityDataSource dataSource = new EntityDataSource(); EntityDataSourcePropertiesHelper.setName(dataSource, link.getDataSource()); EntityDataSourcePropertiesHelper.setEntityId(dataSource, link.getId()); return dataSource; } ).collect(Collectors.toList())) .orElse(new ArrayList<>()); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity, IterableStream.of(entityDataSources)); final HealthcareAssertion assertion = entity.getAssertion(); if (assertion != null) { HealthcareEntityPropertiesHelper.setAssertion(healthcareEntity, toHealthcareEntityAssertion(assertion)); } return healthcareEntity; }).collect(Collectors.toList()); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(analyzeHealthcareEntitiesResult, IterableStream.of(healthcareEntities)); final List<HealthcareEntityRelation> healthcareEntityRelations = documentEntities.getRelations().stream().map( healthcareRelation -> { final HealthcareEntityRelation entityRelation = new HealthcareEntityRelation(); final RelationType relationType = healthcareRelation.getRelationType(); if (relationType != null) { HealthcareEntityRelationPropertiesHelper.setRelationType(entityRelation, HealthcareEntityRelationType.fromString(relationType.toString())); } final List<HealthcareEntityRelationRole> relationRoles = healthcareRelation.getEntities().stream().map( relationEntity -> { final HealthcareEntityRelationRole relationRole = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(relationRole, relationEntity.getRole()); HealthcareEntityRelationRolePropertiesHelper.setEntity(relationRole, healthcareEntities.get(getHealthcareEntityIndex(relationEntity.getRef()))); return relationRole; }).collect(Collectors.toList()); HealthcareEntityRelationPropertiesHelper.setRoles(entityRelation, IterableStream.of(relationRoles)); return entityRelation; }).collect(Collectors.toList()); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(analyzeHealthcareEntitiesResult, IterableStream.of(healthcareEntityRelations)); analyzeHealthcareEntitiesResults.add(analyzeHealthcareEntitiesResult); }); healthcareResult.getErrors().forEach(documentError -> analyzeHealthcareEntitiesResults.add(new AnalyzeHealthcareEntitiesResult( documentError.getId(), null, toTextAnalyticsError(documentError.getError()))) ); return new AnalyzeHealthcareEntitiesResultCollection(IterableStream.of(analyzeHealthcareEntitiesResults)); } public static HealthcareEntityAssertion toHealthcareEntityAssertion(HealthcareAssertion healthcareAssertion) { final Association association = healthcareAssertion.getAssociation(); final Certainty certainty = healthcareAssertion.getCertainty(); final Conditionality conditionality = healthcareAssertion.getConditionality(); final HealthcareEntityAssertion entityAssertion = new HealthcareEntityAssertion(); if (association != null) { HealthcareEntityAssertionPropertiesHelper.setAssociation(entityAssertion, EntityAssociation.fromString(association.toString())); } if (certainty != null) { HealthcareEntityAssertionPropertiesHelper.setCertainty(entityAssertion, toCertainty(certainty)); } if (conditionality != null) { HealthcareEntityAssertionPropertiesHelper.setConditionality(entityAssertion, toConditionality(conditionality)); } return entityAssertion; } private static EntityCertainty toCertainty(Certainty certainty) { EntityCertainty entityCertainty1 = null; switch (certainty) { case POSITIVE: entityCertainty1 = EntityCertainty.POSITIVE; break; case POSITIVE_POSSIBLE: entityCertainty1 = EntityCertainty.POSITIVE_POSSIBLE; break; case NEUTRAL_POSSIBLE: entityCertainty1 = EntityCertainty.NEUTRAL_POSSIBLE; break; case NEGATIVE_POSSIBLE: entityCertainty1 = EntityCertainty.NEGATIVE_POSSIBLE; break; case NEGATIVE: entityCertainty1 = EntityCertainty.NEGATIVE; break; default: break; } return entityCertainty1; } private static EntityConditionality toConditionality(Conditionality conditionality) { EntityConditionality conditionality1 = null; switch (conditionality) { case HYPOTHETICAL: conditionality1 = EntityConditionality.HYPOTHETICAL; break; case CONDITIONAL: conditionality1 = EntityConditionality.CONDITIONAL; break; default: break; } return conditionality1; } /** * Helper function that parse healthcare entity index from the given entity reference string. * The entity reference format is " * * @param entityReference the given healthcare entity reference string. * * @return the healthcare entity index. */ private static Integer getHealthcareEntityIndex(String entityReference) { if (!CoreUtils.isNullOrEmpty(entityReference)) { int lastIndex = entityReference.lastIndexOf('/'); if (lastIndex != -1) { return Integer.parseInt(entityReference.substring(lastIndex + 1)); } } throw LOGGER.logExceptionAsError( new RuntimeException("Failed to parse healthcare entity index from: " + entityReference)); } /** * Get the non-null {@link Context}. The default value is {@link Context * * @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies. * Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null. * * @return The Context. */ public static Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } /** * Helper function which retrieves the size of an {@link Iterable}. * * @param documents The iterable of documents. * @return Count of documents in the iterable. */ public static int getDocumentCount(Iterable<?> documents) { if (documents instanceof Collection) { return ((Collection<?>) documents).size(); } else { final int[] count = new int[] { 0 }; documents.forEach(ignored -> count[0] += 1); return count[0]; } } /** * Helper function which convert the {@code Iterable<PiiEntityCategory>} to {@code List<PiiCategory>}. * * @param categoriesFilter the iterable of {@link PiiEntityCategory}. * @return the list of {@link PiiCategory}. */ public static List<PiiCategory> toCategoriesFilter(Iterable<PiiEntityCategory> categoriesFilter) { if (categoriesFilter == null) { return null; } final List<PiiCategory> piiCategories = new ArrayList<>(); categoriesFilter.forEach(category -> piiCategories.add(PiiCategory.fromString(category.toString()))); return piiCategories; } /** * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. * * @param documentSentiment The {@link SentimentResponseDocumentsItem} returned by the service. * @param documentSentimentList The document sentiment list returned by the service. * * @return The {@link AnalyzeSentimentResult} to be returned by the SDK. */ private static AnalyzeSentimentResult toAnalyzeSentimentResult(SentimentResponseDocumentsItem documentSentiment, List<SentimentResponseDocumentsItem> documentSentimentList) { final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores(); final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream() .map(sentenceSentiment -> { final SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getConfidenceScores(); final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment(); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment(sentenceSentiment.getText(), TextSentiment.fromString(sentenceSentimentValue == null ? null : sentenceSentimentValue.toString()), new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(), confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive())); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, toSentenceOpinionList(sentenceSentiment, documentSentimentList)); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, sentenceSentiment.getOffset()); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, sentenceSentiment.getLength()); return sentenceSentiment1; }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment(); return new AnalyzeSentimentResult( documentSentiment.getId(), documentSentiment.getStatistics() == null ? null : toTextDocumentStatistics(documentSentiment.getStatistics()), null, new com.azure.ai.textanalytics.models.DocumentSentiment( TextSentiment.fromString(documentSentimentValue == null ? null : documentSentimentValue.toString()), new SentimentConfidenceScores( confidenceScorePerLabel.getNegative(), confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive()), new IterableStream<>(sentenceSentiments), new IterableStream<>(warnings) )); } /* * Transform SentenceSentiment's opinion mining to output that user can use. */ private static IterableStream<SentenceOpinion> toSentenceOpinionList( com.azure.ai.textanalytics.implementation.models.SentenceSentiment sentenceSentiment, List<SentimentResponseDocumentsItem> documentSentimentList) { final List<SentenceTarget> sentenceTargets = sentenceSentiment.getTargets(); if (sentenceTargets == null) { return null; } final List<SentenceOpinion> sentenceOpinions = new ArrayList<>(); sentenceTargets.forEach(sentenceTarget -> { final List<AssessmentSentiment> assessmentSentiments = new ArrayList<>(); sentenceTarget.getRelations().forEach(targetRelation -> { final TargetRelationType targetRelationType = targetRelation.getRelationType(); final String opinionPointer = targetRelation.getRef(); if (TargetRelationType.ASSESSMENT == targetRelationType) { assessmentSentiments.add(toAssessmentSentiment( findSentimentAssessment(opinionPointer, documentSentimentList))); } }); final TargetSentiment targetSentiment = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment, sentenceTarget.getText()); TargetSentimentPropertiesHelper.setSentiment(targetSentiment, TextSentiment.fromString(sentenceTarget.getSentiment().toString())); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment, toSentimentConfidenceScores(sentenceTarget.getConfidenceScores())); TargetSentimentPropertiesHelper.setOffset(targetSentiment, sentenceTarget.getOffset()); TargetSentimentPropertiesHelper.setLength(targetSentiment, sentenceTarget.getLength()); final SentenceOpinion sentenceOpinion = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion, targetSentiment); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion, new IterableStream<>(assessmentSentiments)); sentenceOpinions.add(sentenceOpinion); }); return new IterableStream<>(sentenceOpinions); } /* * Transform type TargetConfidenceScoreLabel to SentimentConfidenceScores. */ private static SentimentConfidenceScores toSentimentConfidenceScores( TargetConfidenceScoreLabel targetConfidenceScoreLabel) { return new SentimentConfidenceScores(targetConfidenceScoreLabel.getNegative(), NEUTRAL_SCORE_ZERO, targetConfidenceScoreLabel.getPositive()); } /* * Transform type SentenceOpinion to OpinionSentiment. */ private static AssessmentSentiment toAssessmentSentiment(SentenceAssessment sentenceAssessment) { final AssessmentSentiment assessmentSentiment = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment, sentenceAssessment.getText()); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment, TextSentiment.fromString(sentenceAssessment.getSentiment().toString())); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment, toSentimentConfidenceScores(sentenceAssessment.getConfidenceScores())); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment, sentenceAssessment.isNegated()); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment, sentenceAssessment.getOffset()); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment, sentenceAssessment.getLength()); return assessmentSentiment; } private static ExtractSummaryResult toExtractSummaryResult( ExtractiveSummarizationResultDocumentsItem documentSummary) { final List<ExtractedSummarySentence> sentences = documentSummary.getSentences(); final List<SummarySentence> summarySentences = sentences.stream().map(sentence -> { final SummarySentence summarySentence = new SummarySentence(); SummarySentencePropertiesHelper.setText(summarySentence, sentence.getText()); SummarySentencePropertiesHelper.setRankScore(summarySentence, sentence.getRankScore()); SummarySentencePropertiesHelper.setLength(summarySentence, sentence.getLength()); SummarySentencePropertiesHelper.setOffset(summarySentence, sentence.getOffset()); return summarySentence; }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSummary.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); final SummarySentenceCollection summarySentenceCollection = new SummarySentenceCollection( new IterableStream<>(summarySentences), new IterableStream<>(warnings) ); final ExtractSummaryResult extractSummaryResult = new ExtractSummaryResult(documentSummary.getId(), documentSummary.getStatistics() == null ? null : toTextDocumentStatistics(documentSummary.getStatistics()), null ); ExtractSummaryResultPropertiesHelper.setSentences(extractSummaryResult, summarySentenceCollection); return extractSummaryResult; } /** * Helper method to convert {@link CustomEntitiesResult} to {@link RecognizeCustomEntitiesResultCollection}. * * @param customEntitiesResult The {@link CustomEntitiesResult}. * * @return A {@link RecognizeCustomEntitiesResultCollection}. */ public static RecognizeCustomEntitiesResultCollection toRecognizeCustomEntitiesResultCollection( CustomEntitiesResult customEntitiesResult) { final List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); final List<CustomEntitiesResultDocumentsItem> customEntitiesResultDocuments = customEntitiesResult.getDocuments(); for (CustomEntitiesResultDocumentsItem documentSummary : customEntitiesResultDocuments) { recognizeEntitiesResults.add(toRecognizeEntitiesResult(documentSummary)); } for (DocumentError documentError : customEntitiesResult.getErrors()) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } final RecognizeCustomEntitiesResultCollection resultCollection = new RecognizeCustomEntitiesResultCollection(recognizeEntitiesResults); RecognizeCustomEntitiesResultCollectionPropertiesHelper.setProjectName(resultCollection, customEntitiesResult.getProjectName()); RecognizeCustomEntitiesResultCollectionPropertiesHelper.setDeploymentName(resultCollection, customEntitiesResult.getDeploymentName()); if (customEntitiesResult.getStatistics() != null) { RecognizeCustomEntitiesResultCollectionPropertiesHelper.setStatistics(resultCollection, toBatchStatistics(customEntitiesResult.getStatistics())); } return resultCollection; } /** * Helper method to convert {@link CustomSingleClassificationResult} to * {@link SingleCategoryClassifyResultCollection}. * * @param customSingleClassificationResult The {@link CustomSingleClassificationResult}. * * @return A {@link SingleCategoryClassifyResultCollection}. */ public static SingleCategoryClassifyResultCollection toSingleCategoryClassifyResultCollection( CustomSingleLabelClassificationResult customSingleClassificationResult) { final List<SingleCategoryClassifyResult> singleCategoryClassifyResults = new ArrayList<>(); final List<CustomSingleLabelClassificationResultDocumentsItem> singleClassificationDocuments = customSingleClassificationResult.getDocuments(); for (CustomSingleLabelClassificationResultDocumentsItem documentSummary : singleClassificationDocuments) { singleCategoryClassifyResults.add(toSingleCategoryClassifyResult(documentSummary)); } for (DocumentError documentError : customSingleClassificationResult.getErrors()) { singleCategoryClassifyResults.add(new SingleCategoryClassifyResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()))); } final SingleCategoryClassifyResultCollection resultCollection = new SingleCategoryClassifyResultCollection(singleCategoryClassifyResults); SingleCategoryClassifyResultCollectionPropertiesHelper.setProjectName(resultCollection, customSingleClassificationResult.getProjectName()); SingleCategoryClassifyResultCollectionPropertiesHelper.setDeploymentName(resultCollection, customSingleClassificationResult.getDeploymentName()); if (customSingleClassificationResult.getStatistics() != null) { SingleCategoryClassifyResultCollectionPropertiesHelper.setStatistics(resultCollection, toBatchStatistics(customSingleClassificationResult.getStatistics())); } return resultCollection; } private static SingleCategoryClassifyResult toSingleCategoryClassifyResult( CustomSingleLabelClassificationResultDocumentsItem singleClassificationDocument) { final ClassificationResult classificationResult = singleClassificationDocument.getClassProperty(); final List<TextAnalyticsWarning> warnings = singleClassificationDocument.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); final SingleCategoryClassifyResult singleCategoryClassifyResult = new SingleCategoryClassifyResult( singleClassificationDocument.getId(), singleClassificationDocument.getStatistics() == null ? null : toTextDocumentStatistics(singleClassificationDocument.getStatistics()), null); SingleCategoryClassifyResultPropertiesHelper.setClassification(singleCategoryClassifyResult, toDocumentClassification(classificationResult)); SingleCategoryClassifyResultPropertiesHelper.setWarnings(singleCategoryClassifyResult, new IterableStream<>(warnings)); return singleCategoryClassifyResult; } private static ClassificationCategory toDocumentClassification(ClassificationResult classificationResult) { final ClassificationCategory classificationCategory = new ClassificationCategory(); ClassificationCategoryPropertiesHelper.setCategory(classificationCategory, classificationResult.getCategory()); ClassificationCategoryPropertiesHelper.setConfidenceScore(classificationCategory, classificationResult.getConfidenceScore()); return classificationCategory; } /** * Helper method to convert {@link CustomMultiClassificationResult} to * {@link MultiCategoryClassifyResultCollection}. * * @param customMultiClassificationResult The {@link CustomMultiClassificationResult}. * * @return A {@link SingleCategoryClassifyResultCollection}. */ public static MultiCategoryClassifyResultCollection toMultiCategoryClassifyResultCollection( CustomMultiLabelClassificationResult customMultiClassificationResult) { final List<MultiCategoryClassifyResult> multiCategoryClassifyResults = new ArrayList<>(); final List<CustomMultiLabelClassificationResultDocumentsItem> multiClassificationDocuments = customMultiClassificationResult.getDocuments(); for (CustomMultiLabelClassificationResultDocumentsItem multiClassificationDocument : multiClassificationDocuments) { multiCategoryClassifyResults.add(toMultiCategoryClassifyResult(multiClassificationDocument)); } for (DocumentError documentError : customMultiClassificationResult.getErrors()) { multiCategoryClassifyResults.add(new MultiCategoryClassifyResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()))); } final MultiCategoryClassifyResultCollection resultCollection = new MultiCategoryClassifyResultCollection(multiCategoryClassifyResults); MultiCategoryClassifyResultCollectionPropertiesHelper.setProjectName(resultCollection, customMultiClassificationResult.getProjectName()); MultiCategoryClassifyResultCollectionPropertiesHelper.setDeploymentName(resultCollection, customMultiClassificationResult.getDeploymentName()); if (customMultiClassificationResult.getStatistics() != null) { MultiCategoryClassifyResultCollectionPropertiesHelper.setStatistics(resultCollection, toBatchStatistics(customMultiClassificationResult.getStatistics())); } return resultCollection; } private static MultiCategoryClassifyResult toMultiCategoryClassifyResult( CustomMultiLabelClassificationResultDocumentsItem multiClassificationDocument) { final List<ClassificationCategory> classificationCategories = multiClassificationDocument .getClassProperty() .stream() .map(classificationResult -> toDocumentClassification(classificationResult)) .collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = multiClassificationDocument.getWarnings().stream().map( warning -> toTextAnalyticsWarning(warning)).collect(Collectors.toList()); final MultiCategoryClassifyResult classifySingleCategoryResult = new MultiCategoryClassifyResult( multiClassificationDocument.getId(), multiClassificationDocument.getStatistics() == null ? null : toTextDocumentStatistics(multiClassificationDocument.getStatistics()), null); final ClassificationCategoryCollection classifications = new ClassificationCategoryCollection( new IterableStream<>(classificationCategories)); ClassificationCategoryCollectionPropertiesHelper.setWarnings(classifications, new IterableStream<>(warnings)); MultiCategoryClassifyResultPropertiesHelper.setClassifications(classifySingleCategoryResult, classifications); return classifySingleCategoryResult; } /* * Parses the reference pointer to an index array that contains document, sentence, and opinion indexes. */ public static int[] parseRefPointerToIndexArray(String assessmentPointer) { final Matcher matcher = PATTERN.matcher(assessmentPointer); final boolean isMatched = matcher.find(); final int[] result = new int[3]; if (isMatched) { result[0] = Integer.parseInt(matcher.group(1)); result[1] = Integer.parseInt(matcher.group(2)); result[2] = Integer.parseInt(matcher.group(3)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( String.format("'%s' is not a valid assessment pointer.", assessmentPointer))); } return result; } /* * Find the specific sentence assessment in the document sentiment list by given the assessment reference pointer. */ public static SentenceAssessment findSentimentAssessment(String assessmentPointer, List<SentimentResponseDocumentsItem> documentSentiments) { final int[] assessmentIndexes = parseRefPointerToIndexArray(assessmentPointer); final int documentIndex = assessmentIndexes[0]; final int sentenceIndex = assessmentIndexes[1]; final int assessmentIndex = assessmentIndexes[2]; if (documentIndex >= documentSentiments.size()) { throw LOGGER.logExceptionAsError(new IllegalStateException( String.format("Invalid document index '%s' in '%s'.", documentIndex, assessmentPointer))); } final SentimentResponseDocumentsItem documentsentiment = documentSentiments.get(documentIndex); final List<com.azure.ai.textanalytics.implementation.models.SentenceSentiment> sentenceSentiments = documentsentiment.getSentences(); if (sentenceIndex >= sentenceSentiments.size()) { throw LOGGER.logExceptionAsError(new IllegalStateException( String.format("Invalid sentence index '%s' in '%s'.", sentenceIndex, assessmentPointer))); } final List<SentenceAssessment> assessments = sentenceSentiments.get(sentenceIndex).getAssessments(); if (assessmentIndex >= assessments.size()) { throw LOGGER.logExceptionAsError(new IllegalStateException( String.format("Invalid assessment index '%s' in '%s'.", assessmentIndex, assessmentPointer))); } return assessments.get(assessmentIndex); } }
We should also make a note of the service version default in readme.
private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); }
serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW;
private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); }
class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline}
class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline}
Is `setModelVersion()` no longer supported?
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); List<TextDocumentInput> documents = new ArrayList<>(); for (int i = 0; i < 21; i++) { documents.add(new TextDocumentInput(Integer.toString(i), "We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore" + " the spot! They provide marvelous food and they have a great menu. The chief cook happens to be" + " the owner (I think his name is John Doe) and he is super nice, coming out of the kitchen and " + "greeted us all. We enjoyed very much dining in the place! The Sirloin steak I ordered was tender" + " and juicy, and the place was impeccably clean. You can even pre-order from their online menu at" + " www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! The" + " only complaint I have is the food didn't come fast enough. Overall I highly recommend it!" )); } client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setDisplayName("{tasks_display_name}") .setExtractKeyPhrasesActions(new ExtractKeyPhrasesAction()), new AnalyzeActionsOptions()) .flatMap(result -> { AnalyzeActionsOperationDetail operationDetail = result.getValue(); System.out.printf("Action display name: %s, Successfully completed actions: %d, in-process actions: %d," + " failed actions: %d, total actions: %d%n", operationDetail.getDisplayName(), operationDetail.getSucceededCount(), operationDetail.getInProgressCount(), operationDetail.getFailedCount(), operationDetail.getTotalCount()); return result.getFinalResult(); }) .flatMap(analyzeActionsResultPagedFlux -> analyzeActionsResultPagedFlux.byPage()) .subscribe( perPage -> processAnalyzeActionsResult(perPage), ex -> System.out.println("Error listing pages: " + ex.getMessage()), () -> System.out.println("Successfully listed all pages")); try { TimeUnit.MINUTES.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } }
.setExtractKeyPhrasesActions(new ExtractKeyPhrasesAction()),
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); List<TextDocumentInput> documents = new ArrayList<>(); for (int i = 0; i < 21; i++) { documents.add(new TextDocumentInput(Integer.toString(i), "We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore" + " the spot! They provide marvelous food and they have a great menu. The chief cook happens to be" + " the owner (I think his name is John Doe) and he is super nice, coming out of the kitchen and " + "greeted us all. We enjoyed very much dining in the place! The Sirloin steak I ordered was tender" + " and juicy, and the place was impeccably clean. You can even pre-order from their online menu at" + " www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! The" + " only complaint I have is the food didn't come fast enough. Overall I highly recommend it!" )); } client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setDisplayName("{tasks_display_name}") .setRecognizeEntitiesActions(new RecognizeEntitiesAction()) .setExtractKeyPhrasesActions(new ExtractKeyPhrasesAction()), new AnalyzeActionsOptions()) .flatMap(result -> { AnalyzeActionsOperationDetail operationDetail = result.getValue(); System.out.printf("Action display name: %s, Successfully completed actions: %d, in-process actions: %d," + " failed actions: %d, total actions: %d%n", operationDetail.getDisplayName(), operationDetail.getSucceededCount(), operationDetail.getInProgressCount(), operationDetail.getFailedCount(), operationDetail.getTotalCount()); return result.getFinalResult(); }) .flatMap(analyzeActionsResultPagedFlux -> analyzeActionsResultPagedFlux.byPage()) .subscribe( perPage -> processAnalyzeActionsResult(perPage), ex -> System.out.println("Error listing pages: " + ex.getMessage()), () -> System.out.println("Successfully listed all pages")); try { TimeUnit.MINUTES.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } }
class AnalyzeActionsAsync { /** * Main method to invoke this demo about how to analyze a batch of tasks. * * @param args Unused arguments to the program. */ private static void processAnalyzeActionsResult(PagedResponse<AnalyzeActionsResult> perPage) { System.out.printf("Response code: %d, Continuation Token: %s.%n", perPage.getStatusCode(), perPage.getContinuationToken()); for (AnalyzeActionsResult actionsResult : perPage.getElements()) { System.out.println("Entities recognition action results:"); for (RecognizeEntitiesActionResult actionResult : actionsResult.getRecognizeEntitiesResults()) { if (!actionResult.isError()) { for (RecognizeEntitiesResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { for (CategorizedEntity entity : documentResult.getEntities()) { System.out.printf("\tText: %s, category: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()); } } else { System.out.printf("\tCannot recognize entities. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Entities Recognition action. Error: %s%n", actionResult.getError().getMessage()); } } System.out.println("Key phrases extraction action results:"); for (ExtractKeyPhrasesActionResult actionResult : actionsResult.getExtractKeyPhrasesResults()) { if (!actionResult.isError()) { for (ExtractKeyPhraseResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { System.out.println("\tExtracted phrases:"); for (String keyPhrases : documentResult.getKeyPhrases()) { System.out.printf("\t\t%s.%n", keyPhrases); } } else { System.out.printf("\tCannot extract key phrases. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Key Phrases Extraction action. Error: %s%n", actionResult.getError().getMessage()); } } } } }
class AnalyzeActionsAsync { /** * Main method to invoke this demo about how to analyze a batch of tasks. * * @param args Unused arguments to the program. */ private static void processAnalyzeActionsResult(PagedResponse<AnalyzeActionsResult> perPage) { System.out.printf("Response code: %d, Continuation Token: %s.%n", perPage.getStatusCode(), perPage.getContinuationToken()); for (AnalyzeActionsResult actionsResult : perPage.getElements()) { System.out.println("Entities recognition action results:"); for (RecognizeEntitiesActionResult actionResult : actionsResult.getRecognizeEntitiesResults()) { if (!actionResult.isError()) { for (RecognizeEntitiesResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { for (CategorizedEntity entity : documentResult.getEntities()) { System.out.printf("\tText: %s, category: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()); } } else { System.out.printf("\tCannot recognize entities. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Entities Recognition action. Error: %s%n", actionResult.getError().getMessage()); } } System.out.println("Key phrases extraction action results:"); for (ExtractKeyPhrasesActionResult actionResult : actionsResult.getExtractKeyPhrasesResults()) { if (!actionResult.isError()) { for (ExtractKeyPhraseResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { System.out.println("\tExtracted phrases:"); for (String keyPhrases : documentResult.getKeyPhrases()) { System.out.printf("\t\t%s.%n", keyPhrases); } } else { System.out.printf("\tCannot extract key phrases. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Key Phrases Extraction action. Error: %s%n", actionResult.getError().getMessage()); } } } } }
The method is still supported but trying not to be specific on which model version to set in the sample case.
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); List<TextDocumentInput> documents = new ArrayList<>(); for (int i = 0; i < 21; i++) { documents.add(new TextDocumentInput(Integer.toString(i), "We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore" + " the spot! They provide marvelous food and they have a great menu. The chief cook happens to be" + " the owner (I think his name is John Doe) and he is super nice, coming out of the kitchen and " + "greeted us all. We enjoyed very much dining in the place! The Sirloin steak I ordered was tender" + " and juicy, and the place was impeccably clean. You can even pre-order from their online menu at" + " www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! The" + " only complaint I have is the food didn't come fast enough. Overall I highly recommend it!" )); } client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setDisplayName("{tasks_display_name}") .setExtractKeyPhrasesActions(new ExtractKeyPhrasesAction()), new AnalyzeActionsOptions()) .flatMap(result -> { AnalyzeActionsOperationDetail operationDetail = result.getValue(); System.out.printf("Action display name: %s, Successfully completed actions: %d, in-process actions: %d," + " failed actions: %d, total actions: %d%n", operationDetail.getDisplayName(), operationDetail.getSucceededCount(), operationDetail.getInProgressCount(), operationDetail.getFailedCount(), operationDetail.getTotalCount()); return result.getFinalResult(); }) .flatMap(analyzeActionsResultPagedFlux -> analyzeActionsResultPagedFlux.byPage()) .subscribe( perPage -> processAnalyzeActionsResult(perPage), ex -> System.out.println("Error listing pages: " + ex.getMessage()), () -> System.out.println("Successfully listed all pages")); try { TimeUnit.MINUTES.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } }
.setExtractKeyPhrasesActions(new ExtractKeyPhrasesAction()),
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); List<TextDocumentInput> documents = new ArrayList<>(); for (int i = 0; i < 21; i++) { documents.add(new TextDocumentInput(Integer.toString(i), "We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore" + " the spot! They provide marvelous food and they have a great menu. The chief cook happens to be" + " the owner (I think his name is John Doe) and he is super nice, coming out of the kitchen and " + "greeted us all. We enjoyed very much dining in the place! The Sirloin steak I ordered was tender" + " and juicy, and the place was impeccably clean. You can even pre-order from their online menu at" + " www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! The" + " only complaint I have is the food didn't come fast enough. Overall I highly recommend it!" )); } client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setDisplayName("{tasks_display_name}") .setRecognizeEntitiesActions(new RecognizeEntitiesAction()) .setExtractKeyPhrasesActions(new ExtractKeyPhrasesAction()), new AnalyzeActionsOptions()) .flatMap(result -> { AnalyzeActionsOperationDetail operationDetail = result.getValue(); System.out.printf("Action display name: %s, Successfully completed actions: %d, in-process actions: %d," + " failed actions: %d, total actions: %d%n", operationDetail.getDisplayName(), operationDetail.getSucceededCount(), operationDetail.getInProgressCount(), operationDetail.getFailedCount(), operationDetail.getTotalCount()); return result.getFinalResult(); }) .flatMap(analyzeActionsResultPagedFlux -> analyzeActionsResultPagedFlux.byPage()) .subscribe( perPage -> processAnalyzeActionsResult(perPage), ex -> System.out.println("Error listing pages: " + ex.getMessage()), () -> System.out.println("Successfully listed all pages")); try { TimeUnit.MINUTES.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } }
class AnalyzeActionsAsync { /** * Main method to invoke this demo about how to analyze a batch of tasks. * * @param args Unused arguments to the program. */ private static void processAnalyzeActionsResult(PagedResponse<AnalyzeActionsResult> perPage) { System.out.printf("Response code: %d, Continuation Token: %s.%n", perPage.getStatusCode(), perPage.getContinuationToken()); for (AnalyzeActionsResult actionsResult : perPage.getElements()) { System.out.println("Entities recognition action results:"); for (RecognizeEntitiesActionResult actionResult : actionsResult.getRecognizeEntitiesResults()) { if (!actionResult.isError()) { for (RecognizeEntitiesResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { for (CategorizedEntity entity : documentResult.getEntities()) { System.out.printf("\tText: %s, category: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()); } } else { System.out.printf("\tCannot recognize entities. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Entities Recognition action. Error: %s%n", actionResult.getError().getMessage()); } } System.out.println("Key phrases extraction action results:"); for (ExtractKeyPhrasesActionResult actionResult : actionsResult.getExtractKeyPhrasesResults()) { if (!actionResult.isError()) { for (ExtractKeyPhraseResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { System.out.println("\tExtracted phrases:"); for (String keyPhrases : documentResult.getKeyPhrases()) { System.out.printf("\t\t%s.%n", keyPhrases); } } else { System.out.printf("\tCannot extract key phrases. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Key Phrases Extraction action. Error: %s%n", actionResult.getError().getMessage()); } } } } }
class AnalyzeActionsAsync { /** * Main method to invoke this demo about how to analyze a batch of tasks. * * @param args Unused arguments to the program. */ private static void processAnalyzeActionsResult(PagedResponse<AnalyzeActionsResult> perPage) { System.out.printf("Response code: %d, Continuation Token: %s.%n", perPage.getStatusCode(), perPage.getContinuationToken()); for (AnalyzeActionsResult actionsResult : perPage.getElements()) { System.out.println("Entities recognition action results:"); for (RecognizeEntitiesActionResult actionResult : actionsResult.getRecognizeEntitiesResults()) { if (!actionResult.isError()) { for (RecognizeEntitiesResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { for (CategorizedEntity entity : documentResult.getEntities()) { System.out.printf("\tText: %s, category: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()); } } else { System.out.printf("\tCannot recognize entities. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Entities Recognition action. Error: %s%n", actionResult.getError().getMessage()); } } System.out.println("Key phrases extraction action results:"); for (ExtractKeyPhrasesActionResult actionResult : actionsResult.getExtractKeyPhrasesResults()) { if (!actionResult.isError()) { for (ExtractKeyPhraseResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { System.out.println("\tExtracted phrases:"); for (String keyPhrases : documentResult.getKeyPhrases()) { System.out.printf("\t\t%s.%n", keyPhrases); } } else { System.out.printf("\tCannot extract key phrases. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Key Phrases Extraction action. Error: %s%n", actionResult.getError().getMessage()); } } } } }
Is that preferable to a customization?
public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization implementationModels = customization.getPackage("com.azure.storage.blob.implementation.models"); implementationModels.getClass("BlobHierarchyListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.blob.implementation.util.CustomHierarchicalListingDeserializer.class)"); implementationModels.getClass("BlobPrefix").rename("BlobPrefixInternal"); PackageCustomization models = customization.getPackage("com.azure.storage.blob.models"); models.getClass("PageList").addAnnotation("@JsonDeserialize(using = PageListDeserializer.class)"); models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode"); models.getClass("BlobErrorCode").getProperty("SNAPHOT_OPERATION_RATE_EXCEEDED") .addAnnotation("Deprecated"); ClassCustomization blobHttpHeaders = models.getClass("BlobHttpHeaders"); blobHttpHeaders.getMethod("getContentMd5").getJavadoc().setDescription("Get the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); blobHttpHeaders.getMethod("setContentMd5").getJavadoc().setDescription("Set the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); ClassCustomization blobContainerEncryptionScope = models.getClass("BlobContainerEncryptionScope"); blobContainerEncryptionScope.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobHttpHeaders.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-http-headers\")"); blobContainerEncryptionScope.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-container-encryption-scope\")"); models.getClass("CpkInfo").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"cpk-info\")"); models.getClass("BlobMetrics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Metrics\")"); models.getClass("BlobAnalyticsLogging").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Logging\")"); models.getClass("BlobRetentionPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"RetentionPolicy\")"); models.getClass("BlobServiceStatistics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"StorageServiceStats\")"); models.getClass("BlobSignedIdentifier").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"SignedIdentifier\")"); models.getClass("BlobAccessPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"AccessPolicy\")"); ClassCustomization blobContainerItemProperties = models.getClass("BlobContainerItemProperties"); blobContainerItemProperties.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobContainerItemProperties.getMethod("setIsImmutableStorageWithVersioningEnabled") .rename("setImmutableStorageWithVersioningEnabled"); blobContainerItemProperties.getMethod("setEncryptionScopeOverridePrevented") .replaceParameters("boolean encryptionScopeOverridePrevented"); ClassCustomization block = models.getClass("Block"); block.getMethod("getSizeInt") .rename("getSize") .addAnnotation("@Deprecated") .setReturnType("int", "return (int) this.sizeLong; .getJavadoc() .setDeprecated("Use {@link block.getMethod("setSizeInt") .rename("setSize") .addAnnotation("@Deprecated") .setReturnType("Block", "return %s.setSizeLong((long) sizeInt);", true) .getJavadoc() .setDeprecated("Use {@link ClassCustomization listBlobsIncludeItem = models.getClass("ListBlobsIncludeItem"); listBlobsIncludeItem.renameEnumMember("IMMUTABILITYPOLICY", "IMMUTABILITY_POLICY") .renameEnumMember("LEGALHOLD", "LEGAL_HOLD") .renameEnumMember("DELETEDWITHVERSIONS", "DELETED_WITH_VERSIONS"); }
models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode");
public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization implementationModels = customization.getPackage("com.azure.storage.blob.implementation.models"); implementationModels.getClass("BlobHierarchyListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.blob.implementation.util.CustomHierarchicalListingDeserializer.class)"); implementationModels.getClass("BlobPrefix").rename("BlobPrefixInternal"); PackageCustomization models = customization.getPackage("com.azure.storage.blob.models"); models.getClass("PageList").addAnnotation("@JsonDeserialize(using = PageListDeserializer.class)"); models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode"); ClassCustomization blobHttpHeaders = models.getClass("BlobHttpHeaders"); blobHttpHeaders.getMethod("getContentMd5").getJavadoc().setDescription("Get the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); blobHttpHeaders.getMethod("setContentMd5").getJavadoc().setDescription("Set the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); ClassCustomization blobContainerEncryptionScope = models.getClass("BlobContainerEncryptionScope"); blobContainerEncryptionScope.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobHttpHeaders.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-http-headers\")"); blobContainerEncryptionScope.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-container-encryption-scope\")"); models.getClass("CpkInfo").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"cpk-info\")"); models.getClass("BlobMetrics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Metrics\")"); models.getClass("BlobAnalyticsLogging").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Logging\")"); models.getClass("BlobRetentionPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"RetentionPolicy\")"); models.getClass("BlobServiceStatistics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"StorageServiceStats\")"); models.getClass("BlobSignedIdentifier").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"SignedIdentifier\")"); models.getClass("BlobAccessPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"AccessPolicy\")"); ClassCustomization blobContainerItemProperties = models.getClass("BlobContainerItemProperties"); blobContainerItemProperties.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobContainerItemProperties.getMethod("setIsImmutableStorageWithVersioningEnabled") .rename("setImmutableStorageWithVersioningEnabled"); blobContainerItemProperties.getMethod("setEncryptionScopeOverridePrevented") .replaceParameters("boolean encryptionScopeOverridePrevented"); ClassCustomization block = models.getClass("Block"); block.getMethod("getSizeInt") .rename("getSize") .addAnnotation("@Deprecated") .setReturnType("int", "return (int) this.sizeLong; .getJavadoc() .setDeprecated("Use {@link block.getMethod("setSizeInt") .rename("setSize") .addAnnotation("@Deprecated") .setReturnType("Block", "return %s.setSizeLong((long) sizeInt);", true) .getJavadoc() .setDeprecated("Use {@link ClassCustomization listBlobsIncludeItem = models.getClass("ListBlobsIncludeItem"); listBlobsIncludeItem.renameEnumMember("IMMUTABILITYPOLICY", "IMMUTABILITY_POLICY") .renameEnumMember("LEGALHOLD", "LEGAL_HOLD") .renameEnumMember("DELETEDWITHVERSIONS", "DELETED_WITH_VERSIONS"); }
class BlobStorageCustomization extends Customization { @Override }
class BlobStorageCustomization extends Customization { @Override }
yeah. WIll do it in the next documentation PR. Issue: https://github.com/Azure/azure-sdk-for-java/issues/28835
private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); }
serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW;
private boolean isConsolidatedServiceVersion(TextAnalyticsServiceVersion serviceVersion) { if (serviceVersion == null) { serviceVersion = TextAnalyticsServiceVersion.V2022_04_01_PREVIEW; } return !(TextAnalyticsServiceVersion.V3_0 == serviceVersion || TextAnalyticsServiceVersion.V3_1 == serviceVersion); }
class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline}
class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline}
updated
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Should we check if this is Null to avoid NPE?
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
final Integer taskIndex = Integer.valueOf(targetPair[1]);
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Will add below code in the parseActionErrorTarget ```java if (CoreUtils.isNullOrEmpty(taskNameIdPair[0])) { throw logger.logExceptionAsError(new RuntimeException("Missing task name in the target reference")); } if (CoreUtils.isNullOrEmpty(taskNameIdPair[1])) { throw logger.logExceptionAsError(new RuntimeException("Missing task id in the target reference")); } ```
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
final Integer taskIndex = Integer.valueOf(targetPair[1]);
private AnalyzeActionsResult toAnalyzeActionsResultLanguageApi(AnalyzeTextJobState analyzeJobState) { final TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<AnalyzeTextLROResult> tasksResults = tasksStateTasks.getItems(); final List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); final List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); final List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); final List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); final List<AnalyzeHealthcareEntitiesActionResult> analyzeHealthcareEntitiesActionResults = new ArrayList<>(); final List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); final List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); final List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); final List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); final List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(tasksResults)) { for (int i = 0; i < tasksResults.size(); i++) { final AnalyzeTextLROResult taskResult = tasksResults.get(i); if (taskResult instanceof EntityRecognitionLROResult) { final EntityRecognitionLROResult entityTaskResult = (EntityRecognitionLROResult) taskResult; final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = entityTaskResult.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityTaskResult.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomEntityRecognitionLROResult) { final CustomEntityRecognitionLROResult customEntityTaskResult = (CustomEntityRecognitionLROResult) taskResult; final RecognizeCustomEntitiesActionResult actionResult = new RecognizeCustomEntitiesActionResult(); final CustomEntitiesResult results = customEntityTaskResult.getResults(); if (results != null) { RecognizeCustomEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeCustomEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customEntityTaskResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customEntityTaskResult.getLastUpdateDateTime()); recognizeCustomEntitiesActionResults.add(actionResult); } else if (taskResult instanceof CustomSingleLabelClassificationLROResult) { final CustomSingleLabelClassificationLROResult customSingleLabelClassificationResult = (CustomSingleLabelClassificationLROResult) taskResult; final SingleCategoryClassifyActionResult actionResult = new SingleCategoryClassifyActionResult(); final CustomSingleLabelClassificationResult results = customSingleLabelClassificationResult.getResults(); if (results != null) { SingleCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toSingleCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customSingleLabelClassificationResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customSingleLabelClassificationResult.getLastUpdateDateTime()); singleCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof CustomMultiLabelClassificationLROResult) { final CustomMultiLabelClassificationLROResult customMultiLabelClassificationLROResult = (CustomMultiLabelClassificationLROResult) taskResult; final MultiCategoryClassifyActionResult actionResult = new MultiCategoryClassifyActionResult(); final CustomMultiLabelClassificationResult results = customMultiLabelClassificationLROResult.getResults(); if (results != null) { MultiCategoryClassifyActionResultPropertiesHelper.setDocumentsResults(actionResult, toMultiCategoryClassifyResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, customMultiLabelClassificationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, customMultiLabelClassificationLROResult.getLastUpdateDateTime()); multiCategoryClassifyActionResults.add(actionResult); } else if (taskResult instanceof EntityLinkingLROResult) { final EntityLinkingLROResult entityLinkingLROResult = (EntityLinkingLROResult) taskResult; final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = entityLinkingLROResult.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, entityLinkingLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, entityLinkingLROResult.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } else if (taskResult instanceof PiiEntityRecognitionLROResult) { final PiiEntityRecognitionLROResult piiEntityRecognitionLROResult = (PiiEntityRecognitionLROResult) taskResult; final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = piiEntityRecognitionLROResult.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, piiEntityRecognitionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, piiEntityRecognitionLROResult.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } else if (taskResult instanceof ExtractiveSummarizationLROResult) { final ExtractiveSummarizationLROResult extractiveSummarizationLROResult = (ExtractiveSummarizationLROResult) taskResult; final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = extractiveSummarizationLROResult.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, extractiveSummarizationLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, extractiveSummarizationLROResult.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } else if (taskResult instanceof HealthcareLROResult) { final HealthcareLROResult healthcareLROResult = (HealthcareLROResult) taskResult; final AnalyzeHealthcareEntitiesActionResult actionResult = new AnalyzeHealthcareEntitiesActionResult(); final HealthcareResult results = healthcareLROResult.getResults(); if (results != null) { AnalyzeHealthcareEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeHealthcareEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, healthcareLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, healthcareLROResult.getLastUpdateDateTime()); analyzeHealthcareEntitiesActionResults.add(actionResult); } else if (taskResult instanceof SentimentLROResult) { final SentimentLROResult sentimentLROResult = (SentimentLROResult) taskResult; final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = sentimentLROResult.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, sentimentLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, sentimentLROResult.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } else if (taskResult instanceof KeyPhraseExtractionLROResult) { final KeyPhraseExtractionLROResult keyPhraseExtractionLROResult = (KeyPhraseExtractionLROResult) taskResult; final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = keyPhraseExtractionLROResult.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, keyPhraseExtractionLROResult.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, keyPhraseExtractionLROResult.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid Long running operation task result: " + taskResult.getClass())); } } } final List<Error> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (Error error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeHealthcareEntitiesResults(analyzeActionsResult, IterableStream.of(analyzeHealthcareEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String CUSTOM_ENTITY_RECOGNITION_TASKS = "customEntityRecognitionTasks"; private static final String CUSTOM_SINGLE_CLASSIFICATION_TASKS = "customClassificationTasks"; private static final String CUSTOM_MULTI_CLASSIFICATION_TASKS = "customMultiClassificationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_PII_TASKS, ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS, CUSTOM_ENTITY_RECOGNITION_TASKS, CUSTOM_SINGLE_CLASSIFICATION_TASKS, CUSTOM_MULTI_CLASSIFICATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl legacyService; private final AnalyzeTextsImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl legacyService) { this.legacyService = legacyService; this.service = null; } AnalyzeActionsAsyncClient(AnalyzeTextsImpl service) { this.legacyService = null; this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { final AnalyzeTextJobsInput analyzeTextJobsInput = new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput( new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync(analyzeTextJobsInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId( analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (pollingContext, pollResponse) -> Mono.just(pollingContext.getLatestResponse().getValue()), fetchingOperation( operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (pollingContext, activationResponse) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { Objects.requireNonNull(actions, "'actions' cannot be null."); inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); if (service != null) { return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.submitJobWithResponseAsync( new AnalyzeTextJobsInput() .setDisplayName(actions.getDisplayName()) .setAnalysisInput(new MultiLanguageAnalysisInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getAnalyzeTextLROTasks(actions)), finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperationLanguageApi(operationId -> service.jobStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( legacyService.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> legacyService.analyzeStatusWithResponseAsync(operationId.toString(), finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<AnalyzeTextLROTask> getAnalyzeTextLROTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final List<AnalyzeTextLROTask> tasks = new ArrayList<>(); final Iterable<RecognizeEntitiesAction> recognizeEntitiesActions = actions.getRecognizeEntitiesActions(); final Iterable<RecognizePiiEntitiesAction> recognizePiiEntitiesActions = actions.getRecognizePiiEntitiesActions(); final Iterable<ExtractKeyPhrasesAction> extractKeyPhrasesActions = actions.getExtractKeyPhrasesActions(); final Iterable<RecognizeLinkedEntitiesAction> recognizeLinkedEntitiesActions = actions.getRecognizeLinkedEntitiesActions(); final Iterable<AnalyzeHealthcareEntitiesAction> analyzeHealthcareEntitiesActions = actions.getAnalyzeHealthcareEntitiesActions(); final Iterable<AnalyzeSentimentAction> analyzeSentimentActions = actions.getAnalyzeSentimentActions(); final Iterable<ExtractSummaryAction> extractSummaryActions = actions.getExtractSummaryActions(); final Iterable<RecognizeCustomEntitiesAction> recognizeCustomEntitiesActions = actions.getRecognizeCustomEntitiesActions(); final Iterable<SingleCategoryClassifyAction> singleCategoryClassifyActions = actions.getSingleCategoryClassifyActions(); final Iterable<MultiCategoryClassifyAction> multiCategoryClassifyActions = actions.getMultiCategoryClassifyActions(); if (recognizeEntitiesActions != null) { recognizeEntitiesActions.forEach(action -> tasks.add(toEntitiesLROTask(action))); } if (recognizePiiEntitiesActions != null) { recognizePiiEntitiesActions.forEach(action -> tasks.add(toPiiLROTask(action))); } if (analyzeHealthcareEntitiesActions != null) { analyzeHealthcareEntitiesActions.forEach(action -> tasks.add(toHealthcareLROTask(action))); } if (extractKeyPhrasesActions != null) { extractKeyPhrasesActions.forEach(action -> tasks.add(toKeyPhraseLROTask(action))); } if (recognizeLinkedEntitiesActions != null) { recognizeLinkedEntitiesActions.forEach(action -> tasks.add(toEntityLinkingLROTask(action))); } if (analyzeSentimentActions != null) { analyzeSentimentActions.forEach(action -> tasks.add(toSentimentAnalysisLROTask(action))); } if (extractSummaryActions != null) { extractSummaryActions.forEach(action -> tasks.add(toExtractiveSummarizationLROTask(action))); } if (recognizeCustomEntitiesActions != null) { recognizeCustomEntitiesActions.forEach(action -> tasks.add(toCustomEntitiesLROTask(action))); } if (singleCategoryClassifyActions != null) { singleCategoryClassifyActions.forEach(action -> tasks.add( toCustomSingleLabelClassificationLROTask(action))); } if (multiCategoryClassifyActions != null) { multiCategoryClassifyActions.forEach(action -> tasks.add(toCustomMultiLabelClassificationLROTask(action))); } return tasks; } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTasks(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTasks(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTasks(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTasks(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTasks(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } if (actions.getRecognizeCustomEntitiesActions() != null) { jobManifestTasks.setCustomEntityRecognitionTasks(toCustomEntitiesTask(actions)); } if (actions.getSingleCategoryClassifyActions() != null) { jobManifestTasks.setCustomSingleClassificationTasks(toCustomSingleClassificationTask(actions)); } if (actions.getMultiCategoryClassifyActions() != null) { jobManifestTasks.setCustomMultiClassificationTasks(toCustomMultiClassificationTask(actions)); } return jobManifestTasks; } private EntitiesLROTask toEntitiesLROTask(RecognizeEntitiesAction action) { if (action == null) { return null; } final EntitiesLROTask task = new EntitiesLROTask(); task.setParameters(getEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntitiesTask> toEntitiesTasks(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { entitiesTasks.add( action == null ? null : new EntitiesTask() .setTaskName(action.getActionName()) .setParameters(getEntitiesTaskParameters(action))); } return entitiesTasks; } private EntitiesTaskParameters getEntitiesTaskParameters(RecognizeEntitiesAction action) { return (EntitiesTaskParameters) new EntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private PiiLROTask toPiiLROTask(RecognizePiiEntitiesAction action) { if (action == null) { return null; } final PiiLROTask task = new PiiLROTask(); task.setParameters(getPiiTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<PiiTask> toPiiTasks(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { piiTasks.add( action == null ? null : new PiiTask() .setTaskName(action.getActionName()) .setParameters(getPiiTaskParameters(action))); } return piiTasks; } private PiiTaskParameters getPiiTaskParameters(RecognizePiiEntitiesAction action) { return (PiiTaskParameters) new PiiTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setDomain(PiiDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private HealthcareLROTask toHealthcareLROTask(AnalyzeHealthcareEntitiesAction action) { if (action == null) { return null; } final HealthcareLROTask task = new HealthcareLROTask(); task.setParameters(getHealthcareTaskParameters(action)).setTaskName(action.getActionName()); return task; } private HealthcareTaskParameters getHealthcareTaskParameters(AnalyzeHealthcareEntitiesAction action) { return (HealthcareTaskParameters) new HealthcareTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private KeyPhraseLROTask toKeyPhraseLROTask(ExtractKeyPhrasesAction action) { if (action == null) { return null; } final KeyPhraseLROTask task = new KeyPhraseLROTask(); task.setParameters(getKeyPhraseTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<KeyPhrasesTask> toKeyPhrasesTasks(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { keyPhrasesTasks.add( action == null ? null : new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters(getKeyPhraseTaskParameters(action))); } return keyPhrasesTasks; } private KeyPhraseTaskParameters getKeyPhraseTaskParameters(ExtractKeyPhrasesAction action) { return (KeyPhraseTaskParameters) new KeyPhraseTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private EntityLinkingLROTask toEntityLinkingLROTask(RecognizeLinkedEntitiesAction action) { if (action == null) { return null; } final EntityLinkingLROTask task = new EntityLinkingLROTask(); task.setParameters(getEntityLinkingTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<EntityLinkingTask> toEntityLinkingTasks(TextAnalyticsActions actions) { final List<EntityLinkingTask> tasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { tasks.add( action == null ? null : new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters(getEntityLinkingTaskParameters(action))); } return tasks; } private EntityLinkingTaskParameters getEntityLinkingTaskParameters(RecognizeLinkedEntitiesAction action) { return (EntityLinkingTaskParameters) new EntityLinkingTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private SentimentAnalysisLROTask toSentimentAnalysisLROTask(AnalyzeSentimentAction action) { if (action == null) { return null; } final SentimentAnalysisLROTask task = new SentimentAnalysisLROTask(); task.setParameters(getSentimentAnalysisTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<SentimentAnalysisTask> toSentimentAnalysisTasks(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> tasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { tasks.add( action == null ? null : new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters(getSentimentAnalysisTaskParameters(action))); } return tasks; } private SentimentAnalysisTaskParameters getSentimentAnalysisTaskParameters(AnalyzeSentimentAction action) { return (SentimentAnalysisTaskParameters) new SentimentAnalysisTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setOpinionMining(action.isIncludeOpinionMining()) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private ExtractiveSummarizationLROTask toExtractiveSummarizationLROTask(ExtractSummaryAction action) { if (action == null) { return null; } final ExtractiveSummarizationLROTask task = new ExtractiveSummarizationLROTask(); task.setParameters(getExtractiveSummarizationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { extractiveSummarizationTasks.add( action == null ? null : new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters(getExtractiveSummarizationTaskParameters(action))); } return extractiveSummarizationTasks; } private ExtractiveSummarizationTaskParameters getExtractiveSummarizationTaskParameters( ExtractSummaryAction action) { return (ExtractiveSummarizationTaskParameters) new ExtractiveSummarizationTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationSortingCriteria .fromString(action.getOrderBy().toString())) .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomEntitiesLROTask toCustomEntitiesLROTask(RecognizeCustomEntitiesAction action) { if (action == null) { return null; } final CustomEntitiesLROTask task = new CustomEntitiesLROTask(); task.setParameters(getCustomEntitiesTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomEntitiesTask> toCustomEntitiesTask(TextAnalyticsActions actions) { final List<CustomEntitiesTask> tasks = new ArrayList<>(); for (RecognizeCustomEntitiesAction action : actions.getRecognizeCustomEntitiesActions()) { tasks.add( action == null ? null : new CustomEntitiesTask() .setTaskName(action.getActionName()) .setParameters(getCustomEntitiesTaskParameters(action))); } return tasks; } private CustomEntitiesTaskParameters getCustomEntitiesTaskParameters(RecognizeCustomEntitiesAction action) { return (CustomEntitiesTaskParameters) new CustomEntitiesTaskParameters() .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomSingleLabelClassificationLROTask toCustomSingleLabelClassificationLROTask( SingleCategoryClassifyAction action) { if (action == null) { return null; } final CustomSingleLabelClassificationLROTask task = new CustomSingleLabelClassificationLROTask(); task.setParameters(getCustomSingleClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomSingleClassificationTask> toCustomSingleClassificationTask(TextAnalyticsActions actions) { final List<CustomSingleClassificationTask> tasks = new ArrayList<>(); for (SingleCategoryClassifyAction action : actions.getSingleCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomSingleClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomSingleClassificationTaskParameters(action))); } return tasks; } private CustomSingleLabelClassificationTaskParameters getCustomSingleClassificationTaskParameters( SingleCategoryClassifyAction action) { return (CustomSingleLabelClassificationTaskParameters) new CustomSingleLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private CustomMultiLabelClassificationLROTask toCustomMultiLabelClassificationLROTask( MultiCategoryClassifyAction action) { if (action == null) { return null; } final CustomMultiLabelClassificationLROTask task = new CustomMultiLabelClassificationLROTask(); task.setParameters(getCustomMultiLabelClassificationTaskParameters(action)).setTaskName(action.getActionName()); return task; } private List<CustomMultiClassificationTask> toCustomMultiClassificationTask(TextAnalyticsActions actions) { final List<CustomMultiClassificationTask> tasks = new ArrayList<>(); for (MultiCategoryClassifyAction action : actions.getMultiCategoryClassifyActions()) { tasks.add( action == null ? null : new CustomMultiClassificationTask() .setTaskName(action.getActionName()) .setParameters(getCustomMultiLabelClassificationTaskParameters(action))); } return tasks; } private CustomMultiLabelClassificationTaskParameters getCustomMultiLabelClassificationTaskParameters( MultiCategoryClassifyAction action) { return (CustomMultiLabelClassificationTaskParameters) new CustomMultiLabelClassificationTaskParameters() .setProjectName(action.getProjectName()) .setDeploymentName(action.getDeploymentName()) .setLoggingOptOut(action.isServiceLogsDisabled()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<UUID, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperationLanguageApi(Function<UUID, Mono<Response<AnalyzeTextJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final UUID operationId = UUID.fromString(operationResultPollResponse.getValue().getOperationId()); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponseLanguageApi( modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<UUID, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<UUID, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final UUID operationId = UUID.fromString(pollingContext.getLatestResponse().getValue().getOperationId()); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, UUID operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { if (service != null) { return service.jobStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponseLanguageApi) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } return legacyService.analyzeStatusWithResponseAsync(operationId.toString(), showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponseLanguageApi(Response<AnalyzeTextJobState> response) { final AnalyzeTextJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResultLanguageApi(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasksOld tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); List<RecognizeCustomEntitiesActionResult> recognizeCustomEntitiesActionResults = new ArrayList<>(); List<SingleCategoryClassifyActionResult> singleCategoryClassifyActionResults = new ArrayList<>(); List<MultiCategoryClassifyActionResult> multiCategoryClassifyActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { if (error != null) { final String[] targetPair = parseActionErrorTarget(error.getTarget(), error.getMessage()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else if (CUSTOM_ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeCustomEntitiesActionResults.get(taskIndex); } else if (CUSTOM_SINGLE_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = singleCategoryClassifyActionResults.get(taskIndex); } else if (CUSTOM_MULTI_CLASSIFICATION_TASKS.equals(taskName)) { actionResult = multiCategoryClassifyActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getErrorCode() == null ? null : error.getErrorCode().toString()), error.getMessage(), null)); } } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeCustomEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeCustomEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifySingleCategoryResults(analyzeActionsResult, IterableStream.of(singleCategoryClassifyActionResults)); AnalyzeActionsResultPropertiesHelper.setClassifyMultiCategoryResults(analyzeActionsResult, IterableStream.of(multiCategoryClassifyActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasksOld tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponseLanguageApi( Response<AnalyzeTextJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; case PARTIALLY_SUCCEEDED: status = LongRunningOperationStatus.fromString("partiallySucceeded", true); break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference, String errorMessage) { if (CoreUtils.isNullOrEmpty(targetReference)) { if (CoreUtils.isNullOrEmpty(errorMessage)) { errorMessage = "Expected an error with a target field referencing an action but did not get one"; } throw logger.logExceptionAsError(new RuntimeException(errorMessage)); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Could this be done with a Swagger transform?
public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization implementationModels = customization.getPackage("com.azure.storage.blob.implementation.models"); implementationModels.getClass("BlobHierarchyListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.blob.implementation.util.CustomHierarchicalListingDeserializer.class)"); implementationModels.getClass("BlobPrefix").rename("BlobPrefixInternal"); PackageCustomization models = customization.getPackage("com.azure.storage.blob.models"); models.getClass("PageList").addAnnotation("@JsonDeserialize(using = PageListDeserializer.class)"); models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode"); models.getClass("BlobErrorCode").getProperty("SNAPHOT_OPERATION_RATE_EXCEEDED") .addAnnotation("Deprecated"); ClassCustomization blobHttpHeaders = models.getClass("BlobHttpHeaders"); blobHttpHeaders.getMethod("getContentMd5").getJavadoc().setDescription("Get the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); blobHttpHeaders.getMethod("setContentMd5").getJavadoc().setDescription("Set the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); ClassCustomization blobContainerEncryptionScope = models.getClass("BlobContainerEncryptionScope"); blobContainerEncryptionScope.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobHttpHeaders.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-http-headers\")"); blobContainerEncryptionScope.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-container-encryption-scope\")"); models.getClass("CpkInfo").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"cpk-info\")"); models.getClass("BlobMetrics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Metrics\")"); models.getClass("BlobAnalyticsLogging").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Logging\")"); models.getClass("BlobRetentionPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"RetentionPolicy\")"); models.getClass("BlobServiceStatistics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"StorageServiceStats\")"); models.getClass("BlobSignedIdentifier").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"SignedIdentifier\")"); models.getClass("BlobAccessPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"AccessPolicy\")"); ClassCustomization blobContainerItemProperties = models.getClass("BlobContainerItemProperties"); blobContainerItemProperties.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobContainerItemProperties.getMethod("setIsImmutableStorageWithVersioningEnabled") .rename("setImmutableStorageWithVersioningEnabled"); blobContainerItemProperties.getMethod("setEncryptionScopeOverridePrevented") .replaceParameters("boolean encryptionScopeOverridePrevented"); ClassCustomization block = models.getClass("Block"); block.getMethod("getSizeInt") .rename("getSize") .addAnnotation("@Deprecated") .setReturnType("int", "return (int) this.sizeLong; .getJavadoc() .setDeprecated("Use {@link block.getMethod("setSizeInt") .rename("setSize") .addAnnotation("@Deprecated") .setReturnType("Block", "return %s.setSizeLong((long) sizeInt);", true) .getJavadoc() .setDeprecated("Use {@link ClassCustomization listBlobsIncludeItem = models.getClass("ListBlobsIncludeItem"); listBlobsIncludeItem.renameEnumMember("IMMUTABILITYPOLICY", "IMMUTABILITY_POLICY") .renameEnumMember("LEGALHOLD", "LEGAL_HOLD") .renameEnumMember("DELETEDWITHVERSIONS", "DELETED_WITH_VERSIONS"); }
models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode");
public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization implementationModels = customization.getPackage("com.azure.storage.blob.implementation.models"); implementationModels.getClass("BlobHierarchyListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.blob.implementation.util.CustomHierarchicalListingDeserializer.class)"); implementationModels.getClass("BlobPrefix").rename("BlobPrefixInternal"); PackageCustomization models = customization.getPackage("com.azure.storage.blob.models"); models.getClass("PageList").addAnnotation("@JsonDeserialize(using = PageListDeserializer.class)"); models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode"); ClassCustomization blobHttpHeaders = models.getClass("BlobHttpHeaders"); blobHttpHeaders.getMethod("getContentMd5").getJavadoc().setDescription("Get the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); blobHttpHeaders.getMethod("setContentMd5").getJavadoc().setDescription("Set the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); ClassCustomization blobContainerEncryptionScope = models.getClass("BlobContainerEncryptionScope"); blobContainerEncryptionScope.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobHttpHeaders.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-http-headers\")"); blobContainerEncryptionScope.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-container-encryption-scope\")"); models.getClass("CpkInfo").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"cpk-info\")"); models.getClass("BlobMetrics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Metrics\")"); models.getClass("BlobAnalyticsLogging").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Logging\")"); models.getClass("BlobRetentionPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"RetentionPolicy\")"); models.getClass("BlobServiceStatistics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"StorageServiceStats\")"); models.getClass("BlobSignedIdentifier").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"SignedIdentifier\")"); models.getClass("BlobAccessPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"AccessPolicy\")"); ClassCustomization blobContainerItemProperties = models.getClass("BlobContainerItemProperties"); blobContainerItemProperties.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobContainerItemProperties.getMethod("setIsImmutableStorageWithVersioningEnabled") .rename("setImmutableStorageWithVersioningEnabled"); blobContainerItemProperties.getMethod("setEncryptionScopeOverridePrevented") .replaceParameters("boolean encryptionScopeOverridePrevented"); ClassCustomization block = models.getClass("Block"); block.getMethod("getSizeInt") .rename("getSize") .addAnnotation("@Deprecated") .setReturnType("int", "return (int) this.sizeLong; .getJavadoc() .setDeprecated("Use {@link block.getMethod("setSizeInt") .rename("setSize") .addAnnotation("@Deprecated") .setReturnType("Block", "return %s.setSizeLong((long) sizeInt);", true) .getJavadoc() .setDeprecated("Use {@link ClassCustomization listBlobsIncludeItem = models.getClass("ListBlobsIncludeItem"); listBlobsIncludeItem.renameEnumMember("IMMUTABILITYPOLICY", "IMMUTABILITY_POLICY") .renameEnumMember("LEGALHOLD", "LEGAL_HOLD") .renameEnumMember("DELETEDWITHVERSIONS", "DELETED_WITH_VERSIONS"); }
class BlobStorageCustomization extends Customization { @Override }
class BlobStorageCustomization extends Customization { @Override }
Do we want to keep this knowing that the method will throw based on testing it? Maybe comment it out for now until it is fix?
public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization implementationModels = customization.getPackage("com.azure.storage.blob.implementation.models"); implementationModels.getClass("BlobHierarchyListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.blob.implementation.util.CustomHierarchicalListingDeserializer.class)"); implementationModels.getClass("BlobPrefix").rename("BlobPrefixInternal"); PackageCustomization models = customization.getPackage("com.azure.storage.blob.models"); models.getClass("PageList").addAnnotation("@JsonDeserialize(using = PageListDeserializer.class)"); models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode"); models.getClass("BlobErrorCode").getProperty("SNAPHOT_OPERATION_RATE_EXCEEDED") .addAnnotation("Deprecated"); ClassCustomization blobHttpHeaders = models.getClass("BlobHttpHeaders"); blobHttpHeaders.getMethod("getContentMd5").getJavadoc().setDescription("Get the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); blobHttpHeaders.getMethod("setContentMd5").getJavadoc().setDescription("Set the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); ClassCustomization blobContainerEncryptionScope = models.getClass("BlobContainerEncryptionScope"); blobContainerEncryptionScope.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobHttpHeaders.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-http-headers\")"); blobContainerEncryptionScope.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-container-encryption-scope\")"); models.getClass("CpkInfo").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"cpk-info\")"); models.getClass("BlobMetrics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Metrics\")"); models.getClass("BlobAnalyticsLogging").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Logging\")"); models.getClass("BlobRetentionPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"RetentionPolicy\")"); models.getClass("BlobServiceStatistics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"StorageServiceStats\")"); models.getClass("BlobSignedIdentifier").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"SignedIdentifier\")"); models.getClass("BlobAccessPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"AccessPolicy\")"); ClassCustomization blobContainerItemProperties = models.getClass("BlobContainerItemProperties"); blobContainerItemProperties.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobContainerItemProperties.getMethod("setIsImmutableStorageWithVersioningEnabled") .rename("setImmutableStorageWithVersioningEnabled"); blobContainerItemProperties.getMethod("setEncryptionScopeOverridePrevented") .replaceParameters("boolean encryptionScopeOverridePrevented"); ClassCustomization block = models.getClass("Block"); block.getMethod("getSizeInt") .rename("getSize") .addAnnotation("@Deprecated") .setReturnType("int", "return (int) this.sizeLong; .getJavadoc() .setDeprecated("Use {@link block.getMethod("setSizeInt") .rename("setSize") .addAnnotation("@Deprecated") .setReturnType("Block", "return %s.setSizeLong((long) sizeInt);", true) .getJavadoc() .setDeprecated("Use {@link ClassCustomization listBlobsIncludeItem = models.getClass("ListBlobsIncludeItem"); listBlobsIncludeItem.renameEnumMember("IMMUTABILITYPOLICY", "IMMUTABILITY_POLICY") .renameEnumMember("LEGALHOLD", "LEGAL_HOLD") .renameEnumMember("DELETEDWITHVERSIONS", "DELETED_WITH_VERSIONS"); }
models.getClass("BlobErrorCode").getProperty("SNAPHOT_OPERATION_RATE_EXCEEDED")
public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization implementationModels = customization.getPackage("com.azure.storage.blob.implementation.models"); implementationModels.getClass("BlobHierarchyListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.blob.implementation.util.CustomHierarchicalListingDeserializer.class)"); implementationModels.getClass("BlobPrefix").rename("BlobPrefixInternal"); PackageCustomization models = customization.getPackage("com.azure.storage.blob.models"); models.getClass("PageList").addAnnotation("@JsonDeserialize(using = PageListDeserializer.class)"); models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode"); ClassCustomization blobHttpHeaders = models.getClass("BlobHttpHeaders"); blobHttpHeaders.getMethod("getContentMd5").getJavadoc().setDescription("Get the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); blobHttpHeaders.getMethod("setContentMd5").getJavadoc().setDescription("Set the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); ClassCustomization blobContainerEncryptionScope = models.getClass("BlobContainerEncryptionScope"); blobContainerEncryptionScope.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobHttpHeaders.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-http-headers\")"); blobContainerEncryptionScope.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-container-encryption-scope\")"); models.getClass("CpkInfo").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"cpk-info\")"); models.getClass("BlobMetrics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Metrics\")"); models.getClass("BlobAnalyticsLogging").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Logging\")"); models.getClass("BlobRetentionPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"RetentionPolicy\")"); models.getClass("BlobServiceStatistics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"StorageServiceStats\")"); models.getClass("BlobSignedIdentifier").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"SignedIdentifier\")"); models.getClass("BlobAccessPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"AccessPolicy\")"); ClassCustomization blobContainerItemProperties = models.getClass("BlobContainerItemProperties"); blobContainerItemProperties.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobContainerItemProperties.getMethod("setIsImmutableStorageWithVersioningEnabled") .rename("setImmutableStorageWithVersioningEnabled"); blobContainerItemProperties.getMethod("setEncryptionScopeOverridePrevented") .replaceParameters("boolean encryptionScopeOverridePrevented"); ClassCustomization block = models.getClass("Block"); block.getMethod("getSizeInt") .rename("getSize") .addAnnotation("@Deprecated") .setReturnType("int", "return (int) this.sizeLong; .getJavadoc() .setDeprecated("Use {@link block.getMethod("setSizeInt") .rename("setSize") .addAnnotation("@Deprecated") .setReturnType("Block", "return %s.setSizeLong((long) sizeInt);", true) .getJavadoc() .setDeprecated("Use {@link ClassCustomization listBlobsIncludeItem = models.getClass("ListBlobsIncludeItem"); listBlobsIncludeItem.renameEnumMember("IMMUTABILITYPOLICY", "IMMUTABILITY_POLICY") .renameEnumMember("LEGALHOLD", "LEGAL_HOLD") .renameEnumMember("DELETEDWITHVERSIONS", "DELETED_WITH_VERSIONS"); }
class BlobStorageCustomization extends Customization { @Override }
class BlobStorageCustomization extends Customization { @Override }
nit, Do we have to use method overload? Might it be easier if just different name?
public SpringServiceImpl withoutGitConfig() { if (isEnterpriseTier()) { return withGitConfig((ConfigurationServiceGitProperty) null); } else { return withGitConfig((ConfigServerGitProperty) null); } }
return withGitConfig((ConfigServerGitProperty) null);
public SpringServiceImpl withoutGitConfig() { return withGitConfig(null); }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private boolean updateConfigurationServiceTask = true; private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringConfigurationServices configurationServices() { return this.configurationServices; } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (updateConfigurationServiceTask) { prepareCreateOrUpdateConfigurationService(); } updateConfigurationServiceTask = false; } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { clearCache(); if (isGroupFaulted) { return Mono.empty(); } return refreshAsync().then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withGitConfig(String uri, String branch, List<String> filePatterns) { return withGitConfigRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitConfigRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.gitRepositoryMap.computeIfAbsent(name, key -> new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch) ); updateConfigurationServiceTask = true; return this; } @Override public SpringServiceImpl withGitConfig(ConfigurationServiceGitProperty gitConfig) { gitRepositoryMap.clear(); if (gitConfig != null && CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.gitRepositoryMap.put(repository.name(), repository); } } updateConfigurationServiceTask = true; return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = new ArrayList<>(this.gitRepositoryMap.values()); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.gitRepositoryMap.clear(); this.configurationServices.clear(); } }
class SpringServiceImpl extends GroupableResourceImpl<SpringService, ServiceResourceInner, SpringServiceImpl, AppPlatformManager> implements SpringService, SpringService.Definition, SpringService.Update { private final SpringServiceCertificatesImpl certificates = new SpringServiceCertificatesImpl(this); private final SpringAppsImpl apps = new SpringAppsImpl(this); private final SpringConfigurationServicesImpl configurationServices = new SpringConfigurationServicesImpl(this); private FunctionalTaskItem configServerTask = null; private FunctionalTaskItem monitoringSettingTask = null; private ServiceResourceInner patchToUpdate = new ServiceResourceInner(); private boolean updated; private final ConfigurationServiceConfig configurationServiceConfig = new ConfigurationServiceConfig(); SpringServiceImpl(String name, ServiceResourceInner innerObject, AppPlatformManager manager) { super(name, innerObject, manager); } @Override public SpringServiceImpl update() { return super.update(); } @Override public Sku sku() { return innerModel().sku(); } @Override public SpringApps apps() { return apps; } @Override public SpringServiceCertificates certificates() { return certificates; } @Override public MonitoringSettingProperties getMonitoringSetting() { return getMonitoringSettingAsync().block(); } @Override public Mono<MonitoringSettingProperties> getMonitoringSettingAsync() { return manager().serviceClient().getMonitoringSettings().getAsync(resourceGroupName(), name()) .map(MonitoringSettingResourceInner::properties); } @Override public ConfigServerProperties getServerProperties() { return getServerPropertiesAsync().block(); } @Override public Mono<ConfigServerProperties> getServerPropertiesAsync() { return manager().serviceClient().getConfigServers().getAsync(resourceGroupName(), name()) .map(ConfigServerResourceInner::properties); } @Override public TestKeys listTestKeys() { return listTestKeysAsync().block(); } @Override public Mono<TestKeys> listTestKeysAsync() { return manager().serviceClient().getServices().listTestKeysAsync(resourceGroupName(), name()); } @Override public TestKeys regenerateTestKeys(TestKeyType keyType) { return regenerateTestKeysAsync(keyType).block(); } @Override public Mono<TestKeys> regenerateTestKeysAsync(TestKeyType keyType) { return manager().serviceClient().getServices().regenerateTestKeyAsync(resourceGroupName(), name(), new RegenerateTestKeyRequestPayload().withKeyType(keyType)); } @Override public void disableTestEndpoint() { disableTestEndpointAsync().block(); } @Override public Mono<Void> disableTestEndpointAsync() { return manager().serviceClient().getServices().disableTestEndpointAsync(resourceGroupName(), name()); } @Override public TestKeys enableTestEndpoint() { return enableTestEndpointAsync().block(); } @Override public Mono<TestKeys> enableTestEndpointAsync() { return manager().serviceClient().getServices().enableTestEndpointAsync(resourceGroupName(), name()); } @Override public SpringConfigurationService getDefaultConfigurationService() { return manager().serviceClient().getConfigurationServices().getAsync(resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME) .switchIfEmpty(Mono.empty()) .map(inner -> new SpringConfigurationServiceImpl(inner.name(), this, inner)) .block(); } @Override public SpringServiceImpl withSku(String skuName) { return withSku(new Sku().withName(skuName)); } @Override public SpringServiceImpl withSku(SkuName skuName) { return withSku(skuName.toString()); } @Override public SpringServiceImpl withSku(String skuName, int capacity) { return withSku(new Sku().withName(skuName).withCapacity(capacity)); } @Override public SpringServiceImpl withSku(Sku sku) { innerModel().withSku(sku); if (isInUpdateMode()) { patchToUpdate.withSku(sku); updated = true; } return this; } @Override public SpringServiceImpl withEnterpriseTierSku() { withSku(SkuName.E0); return this; } @Override public SpringServiceImpl withTracing(String appInsightInstrumentationKey) { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync(resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties() .withAppInsightsInstrumentationKey(appInsightInstrumentationKey) .withTraceEnabled(true))) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withoutTracing() { monitoringSettingTask = context -> manager().serviceClient().getMonitoringSettings() .updatePatchAsync( resourceGroupName(), name(), new MonitoringSettingResourceInner().withProperties( new MonitoringSettingProperties().withTraceEnabled(false) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUri(String uri) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty().withUri(uri) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitUriAndCredential(String uri, String username, String password) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty( new ConfigServerGitProperty() .withUri(uri) .withUsername(username) .withPassword(password) )) )) .then(context.voidMono()); return this; } @Override public SpringServiceImpl withGitConfig(ConfigServerGitProperty gitConfig) { configServerTask = context -> manager().serviceClient().getConfigServers() .updatePatchAsync(resourceGroupName(), name(), new ConfigServerResourceInner().withProperties( new ConfigServerProperties() .withConfigServer(new ConfigServerSettings().withGitProperty(gitConfig)) )) .then(context.voidMono()); return this; } @Override @Override public void beforeGroupCreateOrUpdate() { if (configServerTask != null) { this.addPostRunDependent(configServerTask); } if (monitoringSettingTask != null) { this.addPostRunDependent(monitoringSettingTask); } if (isEnterpriseTier()) { if (isInCreateMode() || configurationServiceConfig.needUpdate()) { prepareCreateOrUpdateConfigurationService(); configurationServiceConfig.clearUpdate(); } } configServerTask = null; monitoringSettingTask = null; } @Override public Mono<SpringService> createResourceAsync() { Mono<ServiceResourceInner> createOrUpdate; if (isInCreateMode()) { createOrUpdate = manager().serviceClient().getServices() .createOrUpdateAsync(resourceGroupName(), name(), innerModel()); if (isEnterpriseTier()) { createOrUpdate = createOrUpdate .flatMap(inner -> manager().serviceClient().getBuildServiceAgentPools().updatePutAsync( resourceGroupName(), name(), Constants.DEFAULT_TANZU_COMPONENT_NAME, Constants.DEFAULT_TANZU_COMPONENT_NAME, new BuildServiceAgentPoolResourceInner() .withProperties( new BuildServiceAgentPoolProperties() .withPoolSize( new BuildServiceAgentPoolSizeProperties() .withName("S1"))) ).then(Mono.just(inner))); } } else if (updated) { createOrUpdate = manager().serviceClient().getServices().updateAsync( resourceGroupName(), name(), patchToUpdate); patchToUpdate = new ServiceResourceInner(); updated = false; } else { return Mono.just(this); } return createOrUpdate .map(inner -> { this.setInner(inner); return this; }); } @Override public Mono<Void> afterPostRunAsync(boolean isGroupFaulted) { return Mono .just(true) .map( ignored -> { clearCache(); return ignored; }) .then(); } @Override protected Mono<ServiceResourceInner> getInnerAsync() { return manager().serviceClient().getServices().getByResourceGroupAsync(resourceGroupName(), name()) .map(inner -> { clearCache(); return inner; }); } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties().withVaultUri(keyVaultUri).withKeyVaultCertName(certNameInKeyVault) ); return this; } @Override public SpringServiceImpl withCertificate(String name, String keyVaultUri, String certNameInKeyVault, String certVersion) { certificates.prepareCreateOrUpdate( name, new KeyVaultCertificateProperties() .withVaultUri(keyVaultUri) .withKeyVaultCertName(certNameInKeyVault) .withCertVersion(certVersion) ); return this; } @Override public SpringServiceImpl withoutCertificate(String name) { certificates.prepareDelete(name); return this; } @Override public SpringServiceImpl withDefaultGitRepository(String uri, String branch, List<String> filePatterns) { return withGitRepository(Constants.DEFAULT_TANZU_COMPONENT_NAME, uri, branch, filePatterns); } @Override public SpringServiceImpl withGitRepository(String name, String uri, String branch, List<String> filePatterns) { if (CoreUtils.isNullOrEmpty(name)) { return this; } this.configurationServiceConfig.addRepository( new ConfigurationServiceGitRepository() .withName(name) .withUri(uri) .withPatterns(filePatterns) .withLabel(branch)); return this; } @Override public SpringServiceImpl withGitRepositoryConfig(ConfigurationServiceGitProperty gitConfig) { this.configurationServiceConfig.clearRepositories(); if (gitConfig != null && !CoreUtils.isNullOrEmpty(gitConfig.repositories())) { for (ConfigurationServiceGitRepository repository : gitConfig.repositories()) { this.configurationServiceConfig.addRepository(repository); } } return this; } @Override public SpringServiceImpl withoutGitRepository(String name) { this.configurationServiceConfig.removeRepository(name); return this; } @Override public SpringServiceImpl withoutGitRepositories() { this.configurationServiceConfig.clearRepositories(); return this; } private void prepareCreateOrUpdateConfigurationService() { List<ConfigurationServiceGitRepository> repositories = this.configurationServiceConfig.mergeRepositories(); this.configurationServices.prepareCreateOrUpdate(new ConfigurationServiceGitProperty().withRepositories(repositories)); } private boolean isInUpdateMode() { return !isInCreateMode(); } boolean isEnterpriseTier() { return innerModel().sku() != null && SkuName.E0.toString().equals(innerModel().sku().name()); } private void clearCache() { this.configurationServices.clear(); this.configurationServiceConfig.reset(); } private class ConfigurationServiceConfig { private final Map<String, ConfigurationServiceGitRepository> gitRepositoryMap = new ConcurrentHashMap<>(); private final Set<String> repositoriesToDelete = new HashSet<>(); private boolean update; private boolean clearRepositories; boolean needUpdate() { return update; } public void clearUpdate() { this.update = false; } void reset() { this.gitRepositoryMap.clear(); this.update = false; this.repositoriesToDelete.clear(); this.clearRepositories = false; } public void addRepository(ConfigurationServiceGitRepository repository) { this.gitRepositoryMap.putIfAbsent(repository.name(), repository); this.update = true; } public void clearRepositories() { this.gitRepositoryMap.clear(); this.clearRepositories = true; this.update = true; } public void removeRepository(String name) { this.repositoriesToDelete.add(name); this.update = true; } public List<ConfigurationServiceGitRepository> mergeRepositories() { if (this.clearRepositories) { return new ArrayList<>(this.gitRepositoryMap.values()); } else { Map<String, ConfigurationServiceGitRepository> existingGitRepositories = new HashMap<>(); if (isInUpdateMode()) { SpringConfigurationService configurationService = getDefaultConfigurationService(); if (configurationService != null) { List<ConfigurationServiceGitRepository> repositoryList = configurationService.innerModel().properties().settings() == null ? Collections.emptyList() : configurationService.innerModel().properties().settings().gitProperty().repositories(); if (repositoryList != null) { repositoryList.forEach(repository -> existingGitRepositories.put(repository.name(), repository)); } } } existingGitRepositories.putAll(gitRepositoryMap); for (String repositoryToDelete : repositoriesToDelete) { existingGitRepositories.remove(repositoryToDelete); } return new ArrayList<>(existingGitRepositories.values()); } } } }
Removed
public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization implementationModels = customization.getPackage("com.azure.storage.blob.implementation.models"); implementationModels.getClass("BlobHierarchyListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.blob.implementation.util.CustomHierarchicalListingDeserializer.class)"); implementationModels.getClass("BlobPrefix").rename("BlobPrefixInternal"); PackageCustomization models = customization.getPackage("com.azure.storage.blob.models"); models.getClass("PageList").addAnnotation("@JsonDeserialize(using = PageListDeserializer.class)"); models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode"); models.getClass("BlobErrorCode").getProperty("SNAPHOT_OPERATION_RATE_EXCEEDED") .addAnnotation("Deprecated"); ClassCustomization blobHttpHeaders = models.getClass("BlobHttpHeaders"); blobHttpHeaders.getMethod("getContentMd5").getJavadoc().setDescription("Get the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); blobHttpHeaders.getMethod("setContentMd5").getJavadoc().setDescription("Set the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); ClassCustomization blobContainerEncryptionScope = models.getClass("BlobContainerEncryptionScope"); blobContainerEncryptionScope.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobHttpHeaders.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-http-headers\")"); blobContainerEncryptionScope.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-container-encryption-scope\")"); models.getClass("CpkInfo").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"cpk-info\")"); models.getClass("BlobMetrics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Metrics\")"); models.getClass("BlobAnalyticsLogging").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Logging\")"); models.getClass("BlobRetentionPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"RetentionPolicy\")"); models.getClass("BlobServiceStatistics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"StorageServiceStats\")"); models.getClass("BlobSignedIdentifier").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"SignedIdentifier\")"); models.getClass("BlobAccessPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"AccessPolicy\")"); ClassCustomization blobContainerItemProperties = models.getClass("BlobContainerItemProperties"); blobContainerItemProperties.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobContainerItemProperties.getMethod("setIsImmutableStorageWithVersioningEnabled") .rename("setImmutableStorageWithVersioningEnabled"); blobContainerItemProperties.getMethod("setEncryptionScopeOverridePrevented") .replaceParameters("boolean encryptionScopeOverridePrevented"); ClassCustomization block = models.getClass("Block"); block.getMethod("getSizeInt") .rename("getSize") .addAnnotation("@Deprecated") .setReturnType("int", "return (int) this.sizeLong; .getJavadoc() .setDeprecated("Use {@link block.getMethod("setSizeInt") .rename("setSize") .addAnnotation("@Deprecated") .setReturnType("Block", "return %s.setSizeLong((long) sizeInt);", true) .getJavadoc() .setDeprecated("Use {@link ClassCustomization listBlobsIncludeItem = models.getClass("ListBlobsIncludeItem"); listBlobsIncludeItem.renameEnumMember("IMMUTABILITYPOLICY", "IMMUTABILITY_POLICY") .renameEnumMember("LEGALHOLD", "LEGAL_HOLD") .renameEnumMember("DELETEDWITHVERSIONS", "DELETED_WITH_VERSIONS"); }
models.getClass("BlobErrorCode").getProperty("SNAPHOT_OPERATION_RATE_EXCEEDED")
public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization implementationModels = customization.getPackage("com.azure.storage.blob.implementation.models"); implementationModels.getClass("BlobHierarchyListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.blob.implementation.util.CustomHierarchicalListingDeserializer.class)"); implementationModels.getClass("BlobPrefix").rename("BlobPrefixInternal"); PackageCustomization models = customization.getPackage("com.azure.storage.blob.models"); models.getClass("PageList").addAnnotation("@JsonDeserialize(using = PageListDeserializer.class)"); models.getClass("BlobCopySourceTags").rename("BlobCopySourceTagsMode"); ClassCustomization blobHttpHeaders = models.getClass("BlobHttpHeaders"); blobHttpHeaders.getMethod("getContentMd5").getJavadoc().setDescription("Get the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); blobHttpHeaders.getMethod("setContentMd5").getJavadoc().setDescription("Set the contentMd5 property: " + "Optional. An MD5 hash of the blob content. Note that this hash is not validated, as the hashes for " + "the individual blocks were validated when each was uploaded. The value does not need to be base64 " + "encoded as the SDK will perform the encoding."); ClassCustomization blobContainerEncryptionScope = models.getClass("BlobContainerEncryptionScope"); blobContainerEncryptionScope.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobHttpHeaders.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-http-headers\")"); blobContainerEncryptionScope.removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"blob-container-encryption-scope\")"); models.getClass("CpkInfo").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"cpk-info\")"); models.getClass("BlobMetrics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Metrics\")"); models.getClass("BlobAnalyticsLogging").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"Logging\")"); models.getClass("BlobRetentionPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"RetentionPolicy\")"); models.getClass("BlobServiceStatistics").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"StorageServiceStats\")"); models.getClass("BlobSignedIdentifier").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"SignedIdentifier\")"); models.getClass("BlobAccessPolicy").removeAnnotation("@JacksonXmlRootElement") .addAnnotation("@JacksonXmlRootElement(localName = \"AccessPolicy\")"); ClassCustomization blobContainerItemProperties = models.getClass("BlobContainerItemProperties"); blobContainerItemProperties.getMethod("isEncryptionScopeOverridePrevented") .setReturnType("boolean", "return Boolean.TRUE.equals(%s);", true); blobContainerItemProperties.getMethod("setIsImmutableStorageWithVersioningEnabled") .rename("setImmutableStorageWithVersioningEnabled"); blobContainerItemProperties.getMethod("setEncryptionScopeOverridePrevented") .replaceParameters("boolean encryptionScopeOverridePrevented"); ClassCustomization block = models.getClass("Block"); block.getMethod("getSizeInt") .rename("getSize") .addAnnotation("@Deprecated") .setReturnType("int", "return (int) this.sizeLong; .getJavadoc() .setDeprecated("Use {@link block.getMethod("setSizeInt") .rename("setSize") .addAnnotation("@Deprecated") .setReturnType("Block", "return %s.setSizeLong((long) sizeInt);", true) .getJavadoc() .setDeprecated("Use {@link ClassCustomization listBlobsIncludeItem = models.getClass("ListBlobsIncludeItem"); listBlobsIncludeItem.renameEnumMember("IMMUTABILITYPOLICY", "IMMUTABILITY_POLICY") .renameEnumMember("LEGALHOLD", "LEGAL_HOLD") .renameEnumMember("DELETEDWITHVERSIONS", "DELETED_WITH_VERSIONS"); }
class BlobStorageCustomization extends Customization { @Override }
class BlobStorageCustomization extends Customization { @Override }
do we need to support different serialization rules (e.g. on null values) at all?
public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); }
if (value.isInitialized()) {
public JsonWriter toJson(JsonWriter jsonWriter) { jsonWriter.writeStartObject().writeStringField("op", op.toString()); if (from != null) { jsonWriter.writeStringField("from", from); } jsonWriter.writeStringField("path", path); if (value.isInitialized()) { String val = value.getValue(); if (val == null) { jsonWriter.writeNullField("value"); } else { jsonWriter.writeRawField("value", val); } } return jsonWriter.writeEndObject().flush(); }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override public String toString() { return toJson(new StringBuilder()).toString(); } @Override public StringBuilder toJson(StringBuilder stringBuilder) { stringBuilder.append("{\"op\":\"") .append(op.toString()) .append("\""); if (from != null) { stringBuilder.append(",\"from\":\"") .append(from) .append("\""); } stringBuilder.append(",\"path\":\"") .append(path) .append("\""); if (value.isInitialized()) { stringBuilder.append(",\"value\":") .append(value.getValue()); } return stringBuilder.append("}"); } @Override /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.deserializeObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }
class JsonPatchOperation implements JsonCapable<JsonPatchOperation> { private final JsonPatchOperationKind op; private final String from; private final String path; private final Option<String> value; /** * Creates a JSON Patch operation. * <p> * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional * to indicate a JSON null. * * @param op The kind of operation. * @param from Optional from target path. * @param path Operation target path. * @param value Optional value. */ public JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option<String> value) { this.op = op; this.from = from; this.path = path; this.value = value; } /** * Gets the operation kind. * * @return The kind of operation. */ public JsonPatchOperationKind getOp() { return op; } /** * Gets the operation from target path. * * @return The operation from target path. */ public String getFrom() { return from; } /** * Gets the operation target path. * * @return The operation target path. */ public String getPath() { return path; } /** * Gets the operation value. * <p> * If the operation doesn't take a value {@link Option * * @return The operation value. */ public Option<String> getValue() { return value; } @Override public int hashCode() { return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); } @Override public boolean equals(Object obj) { if (!(obj instanceof JsonPatchOperation)) { return false; } if (this == obj) { return true; } JsonPatchOperation other = (JsonPatchOperation) obj; return Objects.equals(op, other.op) && Objects.equals(from, other.from) && Objects.equals(path, other.path) && Objects.equals(value, other.value); } @Override public String toString() { return toJson(new StringBuilder()).toString(); } @Override public StringBuilder toJson(StringBuilder stringBuilder) { stringBuilder.append("{\"op\":\"") .append(op.toString()) .append("\""); if (from != null) { stringBuilder.append(",\"from\":\"") .append(from) .append("\""); } stringBuilder.append(",\"path\":\"") .append(path) .append("\""); if (value.isInitialized()) { stringBuilder.append(",\"value\":") .append(value.getValue()); } return stringBuilder.append("}"); } @Override /** * Creates an instance of {@link JsonPatchOperation} by reading the {@link JsonReader}. * <p> * null will be returned if the {@link JsonReader} points to {@link JsonToken * <p> * {@link IllegalStateException} will be thrown if the {@link JsonReader} doesn't point to either {@link * JsonToken * * @param jsonReader The {@link JsonReader} that will be read. * @return An instance of {@link JsonPatchOperation} if the {@link JsonReader} is pointing to {@link * JsonPatchOperation} JSON content, or null if it's pointing to {@link JsonToken * @throws IllegalStateException If the {@link JsonReader} wasn't pointing to either {@link JsonToken * {@link JsonToken */ public static JsonPatchOperation fromJson(JsonReader jsonReader) { return JsonUtils.deserializeObject(jsonReader, (reader, token) -> { JsonPatchOperationKind op = null; String from = null; String path = null; Option<String> value = Option.uninitialized(); while (jsonReader.nextToken() != JsonToken.END_OBJECT) { String fieldName = jsonReader.getFieldName(); token = jsonReader.nextToken(); switch (fieldName) { case "op": op = JsonPatchOperationKind.fromString(jsonReader.getStringValue()); break; case "from": from = jsonReader.getStringValue(); break; case "path": path = jsonReader.getStringValue(); break; case "value": if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) { value = Option.of(jsonReader.readChildren()); } else if (token == JsonToken.NULL) { value = Option.empty(); } else { value = Option.of(jsonReader.getTextValue()); } break; default: break; } } return new JsonPatchOperation(op, from, path, value); }); } }